Form1.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Drawing;
  4. using System.Net;
  5. using System.Timers;
  6. using System.Windows.Forms;
  7. using MvCamCtrl.NET;
  8. using MvCameraControl;
  9. namespace CameraModel
  10. {
  11. public partial class Form1 : Form
  12. {
  13. private const DeviceTLayerType devLayerType = DeviceTLayerType.MvGigEDevice | DeviceTLayerType.MvUsbDevice | DeviceTLayerType.MvGenTLCameraLinkDevice
  14. | DeviceTLayerType.MvGenTLCXPDevice | DeviceTLayerType.MvGenTLXoFDevice;
  15. private IDevice _device = null;
  16. private List<IDeviceInfo> devInfoList = new List<IDeviceInfo>();
  17. private volatile bool isConnected = false;
  18. private volatile bool isSuccess = false;
  19. public delegate void ChangeConnectStatus(bool flag);
  20. public ChangeConnectStatus changeConnectStatus;
  21. public delegate void UpdateDevice();
  22. public UpdateDevice updateDevice;
  23. private System.Timers.Timer timer;
  24. private System.Timers.Timer ConnentedTimer;
  25. private Dictionary<string,string> devices = new Dictionary<string,string>();
  26. private const string ip = "192.168.1.12";
  27. private const string subnet = "255.255.255.0";
  28. private const string gateway = "192.168.1.254";
  29. public Form1()
  30. {
  31. InitializeComponent();
  32. }
  33. public bool IsConnected
  34. {
  35. set { if (value != isConnected) { isConnected = !isConnected;} changeConnectStatus?.Invoke(isConnected); }
  36. get { return isConnected; }
  37. }
  38. public bool IsSuccess
  39. {
  40. set { if (value) { updateDevice.Invoke(); } isSuccess = value; }
  41. get { return isSuccess; }
  42. }
  43. private void Form1_Load(object sender, EventArgs e)
  44. {
  45. changeConnectStatus = (flag) => { ConnectStatusChange(flag); };
  46. updateDevice = () => { updateDeviceSuccess(); };
  47. // ch: 初始化 SDK | en: Initialize SDK
  48. //MyCamera.MV_CC_Initialize_NET();
  49. SDKSystem.Initialize();
  50. // 初始化定时器
  51. InitTimer();
  52. StartTimer();
  53. }
  54. private void updateDeviceSuccess()
  55. {
  56. try
  57. {
  58. if (_device != null)
  59. {
  60. string UserDefinedName = _device.DeviceInfo.UserDefinedName;
  61. if (string.IsNullOrEmpty(UserDefinedName))
  62. {
  63. AntdUI.Message.success(this, "成功修改型号为:" + UserDefinedName, Font, 10);
  64. }
  65. }
  66. }
  67. catch (Exception ex)
  68. {
  69. LogListBox("查看当前设备型号失败!");
  70. LogHelper.LoggerMsg(LogLevel.Error, "查看当前设备型号失败:\t" + ex);
  71. }
  72. finally
  73. {
  74. // 修改完后,相机释放
  75. ReleaseCamera();
  76. pictureBox1.Image = global::CameraModel.Properties.Resources.电力_红灯;
  77. pictureBox2.Image = global::CameraModel.Properties.Resources.电力_红灯;
  78. cbDeviceList.Items.Clear();
  79. cbDeviceList.Text = null;
  80. button_enum.Enabled = true;
  81. button_connect.Enabled = true;
  82. button_update.Enabled = false;
  83. button_clear.Enabled = false;
  84. if (IsSuccess)
  85. {
  86. isSuccess = false;
  87. }
  88. IsConnected = false;
  89. }
  90. }
  91. private void StartTimer()
  92. {
  93. if(timer == null)
  94. {
  95. InitTimer();
  96. }
  97. LogListBox("开始检测设备");
  98. LogHelper.LoggerMsg(LogLevel.Info, "开始检测设备");
  99. timer.Start();
  100. }
  101. private void StopTimer()
  102. {
  103. if (timer != null)
  104. {
  105. LogListBox("停止检测设备");
  106. LogHelper.LoggerMsg(LogLevel.Info, "停止检测设备");
  107. timer.Stop();
  108. }
  109. }
  110. private void ConnectStatusChange(bool flag)
  111. {
  112. if (flag) // 连接
  113. {
  114. // 定时开启检测相机是否还在连接
  115. if (!ConnentedTimer.Enabled)
  116. {
  117. ConnentedTimer.Start();
  118. }
  119. LogListBox("设备已连接");
  120. LogHelper.LoggerMsg(LogLevel.Info, "设备已连接");
  121. if (timer.Enabled)
  122. {
  123. StopTimer();
  124. }
  125. button_enum.Enabled = false;
  126. button_connect.Enabled = false;
  127. button_update.Enabled = true;
  128. button_clear.Enabled = true;
  129. if (_device == null)
  130. {
  131. return;
  132. }
  133. string ModelName = _device.DeviceInfo.ModelName;
  134. // 查找型号
  135. input1.Text = GetDeviceId(ModelName);
  136. if(!string.IsNullOrEmpty(input1.Text) && input1.Text.Length <= 15)
  137. {
  138. // 修改型号
  139. //DeviceUserID
  140. _device.Parameters.SetStringValue("DeviceUserID",input1.Text);
  141. ConnentedTimer.Stop();
  142. LogListBox("型号修改成功," + cbDeviceList.SelectedValue + "=====>" + input1.Text);
  143. IsSuccess = true;
  144. if (!devices.ContainsKey(ModelName))
  145. {
  146. devices.Add(ModelName, input1.Text);
  147. }
  148. }
  149. else
  150. {
  151. LogListBox("输入型号!!!");
  152. }
  153. }
  154. else //断开
  155. {
  156. pictureBox1.Image = global::CameraModel.Properties.Resources.电力_红灯;
  157. pictureBox2.Image = global::CameraModel.Properties.Resources.电力_红灯;
  158. LogListBox("设备已断开!!!");
  159. StartTimer();
  160. cbDeviceList.Items.Clear();
  161. cbDeviceList.Text = null;
  162. button_enum.Enabled = true;
  163. button_connect.Enabled = true;
  164. button_update.Enabled = false;
  165. button_clear.Enabled = false;
  166. }
  167. }
  168. private void ReleaseCamera()
  169. {
  170. LogListBox("设备资源释放成功");
  171. LogListBox("===========================================\n");
  172. //m_MyCamera.MV_CC_CloseDevice_NET();
  173. //m_MyCamera.MV_CC_DestroyDevice_NET();
  174. if (_device != null)
  175. {
  176. _device.StreamGrabber.StopGrabbing();
  177. _device.Close();
  178. _device.Dispose();
  179. _device = null;
  180. }
  181. }
  182. private string GetDeviceId(string ModelName)
  183. {
  184. if (!devices.TryGetValue(ModelName, out string value) && string.IsNullOrEmpty(input1.Text))
  185. {
  186. //AntdUI.Input input = new AntdUI.Input() { Size = new Size(300, 80), MaxLength = 15 };
  187. //if (AntdUI.Modal.open(new AntdUI.Modal.Config(ParentForm, "输入型号", input) { CancelText = null,MaskClosable = false }) == DialogResult.No)
  188. //{
  189. // return "";
  190. //}
  191. //return input.Text;
  192. return "";
  193. }
  194. if (!string.IsNullOrEmpty(input1.Text))
  195. {
  196. return input1.Text;
  197. }
  198. return value;
  199. }
  200. private void InitTimer()
  201. {
  202. if(timer == null)
  203. {
  204. timer = new System.Timers.Timer(3000);
  205. }
  206. timer.AutoReset = true;
  207. timer.Elapsed += OnTimerElapsed;
  208. if (ConnentedTimer == null)
  209. {
  210. ConnentedTimer = new System.Timers.Timer(500);
  211. }
  212. ConnentedTimer.AutoReset = true;
  213. ConnentedTimer.Elapsed += OnConnectedTimerElapsed;
  214. }
  215. private void OnTimerElapsed(object sender, ElapsedEventArgs e)
  216. {
  217. // 检测是否连接
  218. if (_device != null && _device.IsConnected)
  219. {
  220. return;
  221. }
  222. if (!IsConnected) // 未连接
  223. {
  224. Reconnect();
  225. }
  226. }
  227. private void OnConnectedTimerElapsed(object sender, ElapsedEventArgs e)
  228. {
  229. // 检测是否连接
  230. if (_device == null || !_device.IsConnected)
  231. {
  232. IsConnected = false;
  233. }
  234. else
  235. {
  236. IsConnected = true;
  237. }
  238. }
  239. private void Reconnect()
  240. {
  241. if (!IsConnected) // 未连接
  242. {
  243. // 检测连接
  244. if (DeviceListAcq()) // 枚举相机
  245. {
  246. if (OpenDevice()) // 打开相机
  247. {
  248. IsConnected = true;
  249. }
  250. }
  251. }
  252. }
  253. private bool DeviceListAcq()
  254. {
  255. button_update.Enabled = false;
  256. button_clear.Enabled = false;
  257. button_connect.Enabled = false;
  258. devInfoList.Clear();
  259. cbDeviceList.Items.Clear();
  260. // ch:枚举设备 | en:Enum device
  261. int ret = DeviceEnumerator.EnumDevices(devLayerType, out devInfoList);
  262. if (ret != MvError.MV_OK)
  263. {
  264. Console.WriteLine("Enum device failed:{0:x8}", ret);
  265. }
  266. foreach (IDeviceInfo devInfo in devInfoList)
  267. {
  268. cbDeviceList.Items.Add(devInfo.ModelName + ":" + devInfo.UserDefinedName);
  269. }
  270. // ch:选择第一项 | en:Select the first item
  271. if (devInfoList.Count != 0)
  272. {
  273. if (cbDeviceList.InvokeRequired)
  274. {
  275. cbDeviceList.Invoke(new Action(() => {
  276. cbDeviceList.SelectedIndex = 0;
  277. cbDeviceList.Text = cbDeviceList.Items[cbDeviceList.SelectedIndex] + "";
  278. }));
  279. }
  280. else
  281. {
  282. cbDeviceList.SelectedIndex = 0;
  283. cbDeviceList.Text = cbDeviceList.Items[cbDeviceList.SelectedIndex] + "";
  284. }
  285. pictureBox1.Image = global::CameraModel.Properties.Resources.绿灯;
  286. button_connect.Enabled = true;
  287. return true;
  288. }
  289. else
  290. {
  291. LogListBox("没有检测到相机");
  292. button_connect.Enabled = false;
  293. pictureBox1.Image = global::CameraModel.Properties.Resources.电力_红灯;
  294. pictureBox2.Image = global::CameraModel.Properties.Resources.电力_红灯;
  295. return false;
  296. }
  297. }
  298. private bool OpenDevice()
  299. {
  300. bool is_aotu = false;
  301. try
  302. {
  303. int nRet = -1;
  304. button_update.Enabled = false;
  305. button_clear.Enabled = false;
  306. pictureBox2.Image = global::CameraModel.Properties.Resources.电力_红灯;
  307. if (devInfoList.Count == 0 || cbDeviceList.SelectedIndex == -1)
  308. {
  309. LogListBox("没有检测或选择设备!");
  310. return false;
  311. }
  312. is_aotu = timer.Enabled;
  313. if (is_aotu)
  314. {
  315. timer.Stop();
  316. }
  317. // ch:创建设备 | en:Create device
  318. _device = DeviceFactory.CreateDevice(devInfoList[cbDeviceList.SelectedIndex]);
  319. IGigEDevice _IGigEDevice = _device as IGigEDevice;
  320. bool accessible = DeviceEnumerator.IsDeviceAccessible(devInfoList[cbDeviceList.SelectedIndex], DeviceAccessMode.AccessExclusive);
  321. if (accessible)
  322. {
  323. nRet = _IGigEDevice.Open(DeviceAccessMode.AccessControl,0);
  324. if (MvError.MV_OK != nRet)
  325. {
  326. nRet = _IGigEDevice.SetIpConfig(IpConfigType.Static);
  327. if (nRet != MvError.MV_OK)
  328. {
  329. Console.WriteLine("设置静态失败,状态码:" + nRet);
  330. _IGigEDevice.Dispose();
  331. return false;
  332. }
  333. if (SetIp(_IGigEDevice))
  334. {
  335. // 打开并修改
  336. nRet = _IGigEDevice.Open(DeviceAccessMode.AccessControl, 0);
  337. if (MvError.MV_OK != nRet)
  338. {
  339. //m_MyCamera.MV_CC_DestroyDevice_NET();
  340. LogHelper.LoggerMsg(LogLevel.Error, "Device open fail! 打开相机状态码:" + nRet);
  341. LogListBox("Device open fail!");
  342. _IGigEDevice.Dispose();
  343. return false;
  344. }
  345. }
  346. }
  347. pictureBox2.Image = global::CameraModel.Properties.Resources.绿灯;
  348. button_update.Enabled = true;
  349. button_clear.Enabled = true;
  350. return true;
  351. }
  352. else
  353. {
  354. SetIp(_IGigEDevice);
  355. _IGigEDevice.Dispose();
  356. IDeviceInfo deviceInfo = devInfoList[cbDeviceList.SelectedIndex];
  357. IGigEDeviceInfo gigeDevInfo = deviceInfo as IGigEDeviceInfo;
  358. uint nIp1 = ((gigeDevInfo.NetExport & 0xff000000) >> 24);
  359. uint nIp2 = ((gigeDevInfo.NetExport & 0x00ff0000) >> 16);
  360. uint nIp3 = ((gigeDevInfo.NetExport & 0x0000ff00) >> 8);
  361. uint nIp4 = (gigeDevInfo.NetExport & 0x000000ff);
  362. string netExportIp = nIp1.ToString() + "." + nIp2.ToString() + "." + nIp3.ToString() + "." + nIp4.ToString();
  363. //ch:需要重新创建句柄,设置为静态IP方式进行保存 | en: Need to recreate the handle and set it to static IP mode for saving
  364. //ch: 创建设备 | en: Create device
  365. _device = DeviceFactory.CreateDeviceByIp(ip, netExportIp);
  366. if (null == _device)
  367. {
  368. LogListBox("Create handle fail");
  369. return false;
  370. }
  371. _IGigEDevice = _device as IGigEDevice;
  372. nRet = _IGigEDevice.SetIpConfig(IpConfigType.Static);
  373. if (MvError.MV_OK != nRet)
  374. {
  375. LogListBox("Set Ip config fail");
  376. _IGigEDevice.Dispose();
  377. _device = null;
  378. return false;
  379. }
  380. }
  381. return true;
  382. }
  383. catch(Exception ex)
  384. {
  385. LogListBox("打开设备失败:" + ex.Message);
  386. LogHelper.LoggerMsg(LogLevel.Error, "打开设备失败:" + ex);
  387. return false;
  388. }
  389. finally
  390. {
  391. if (is_aotu)
  392. {
  393. timer.Start();
  394. }
  395. }
  396. }
  397. public uint IpToUint(string ipAddress)
  398. {
  399. IPAddress clsIpAddr;
  400. if (false == IPAddress.TryParse(ipAddress, out clsIpAddr))
  401. {
  402. LogListBox("Please enter correct IP");
  403. return 0;
  404. }
  405. return (uint)(IPAddress.NetworkToHostOrder(clsIpAddr.Address) >> 32);
  406. }
  407. private bool SetIp(IGigEDevice _IGigEDevice)
  408. {
  409. uint ipUint = IpToUint(ip);
  410. uint subnetUint = IpToUint(subnet);
  411. uint gatewayUint = IpToUint(gateway);
  412. int nRet = _IGigEDevice.ForceIp(ipUint, subnetUint, gatewayUint); // 重置ip后会自动断连
  413. if (nRet != MvError.MV_OK)
  414. {
  415. Console.WriteLine("设置IP失败,状态码:" + nRet);
  416. _IGigEDevice.Dispose();
  417. return false;
  418. }
  419. return true;
  420. }
  421. private void LogListBox(string content)
  422. {
  423. DateTime dt = DateTime.Now;
  424. if (listBox1.InvokeRequired)
  425. {
  426. listBox1.Invoke(new Action(() => { listBox1.Items.Insert(0, dt.ToString("HH:mm:ss") + " " + content); listBox1.TopIndex = 0; }));
  427. }
  428. else
  429. {
  430. listBox1.Items.Insert(0, dt.ToString("HH:mm:ss") + " " + content);
  431. listBox1.TopIndex = 0;
  432. }
  433. }
  434. private void button_enum_Click(object sender, EventArgs e)
  435. {
  436. DeviceListAcq();
  437. }
  438. private void button_connect_Click(object sender, EventArgs e)
  439. {
  440. OpenDevice();
  441. }
  442. private void button_update_Click(object sender, EventArgs e)
  443. {
  444. // 查找型号
  445. string ModelName = _device.DeviceInfo.ModelName;
  446. string UserName = GetDeviceId(ModelName);
  447. if(String.IsNullOrEmpty(UserName) || UserName.Length > 15)
  448. {
  449. LogListBox("输入型号!!!");
  450. return;
  451. }
  452. input1.Text = UserName;
  453. //m_MyCamera.MV_CC_SetDeviceUserID_NET(input1.Text);
  454. int nRet = _device.Parameters.SetStringValue("DeviceUserID", input1.Text);
  455. if (nRet != MvError.MV_OK)
  456. {
  457. LogListBox("型号修改失败,状态码:" + nRet);
  458. LogHelper.LoggerMsg(LogLevel.Error, "型号修改失败! 状态码:" + nRet);
  459. return;
  460. }
  461. LogListBox("型号," + cbDeviceList.SelectedValue + "=====>" + _device.DeviceInfo.UserDefinedName);
  462. ModelName = _device.DeviceInfo.ModelName;
  463. if (!devices.ContainsKey(ModelName))
  464. {
  465. devices.Add(ModelName, input1.Text);
  466. }
  467. pictureBox1.Image = global::CameraModel.Properties.Resources.电力_红灯;
  468. pictureBox2.Image = global::CameraModel.Properties.Resources.电力_红灯;
  469. if (!DeviceListAcq()) // 枚举相机
  470. {
  471. return;
  472. }
  473. pictureBox1.Image = global::CameraModel.Properties.Resources.绿灯;
  474. if (!OpenDevice()) // 打开相机
  475. {
  476. return;
  477. }
  478. pictureBox2.Image = global::CameraModel.Properties.Resources.绿灯;
  479. }
  480. private void button_clear_Click(object sender, EventArgs e)
  481. {
  482. //m_MyCamera.MV_CC_SetDeviceUserID_NET("");
  483. _device.Parameters.SetStringValue("DeviceUserID", "");
  484. LogListBox("型号清空成功," + cbDeviceList.SelectedValue);
  485. }
  486. private bool isManual = false;
  487. private void button_auto_Click(object sender, EventArgs e)
  488. {
  489. try
  490. {
  491. button_update.Enabled = false;
  492. button_clear.Enabled = false;
  493. pictureBox1.Image = global::CameraModel.Properties.Resources.电力_红灯;
  494. pictureBox2.Image = global::CameraModel.Properties.Resources.电力_红灯;
  495. if (!isManual)
  496. {
  497. if (timer != null && timer.Enabled)
  498. {
  499. timer.Stop();
  500. }
  501. if (ConnentedTimer != null && ConnentedTimer.Enabled)
  502. {
  503. ConnentedTimer.Stop();
  504. }
  505. LogListBox("开启手动模式");
  506. button_auto.Text = "开启自动";
  507. button_auto.DefaultBack = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(152)))), ((int)(((byte)(0)))));
  508. }
  509. else
  510. {
  511. ReleaseCamera();
  512. if (timer != null && !timer.Enabled)
  513. {
  514. timer.Start();
  515. }
  516. LogListBox("开启自动模式");
  517. button_auto.Text = "开启手动";
  518. button_auto.DefaultBack = System.Drawing.Color.FromArgb(((int)(((byte)(3)))), ((int)(((byte)(169)))), ((int)(((byte)(244)))));
  519. }
  520. }
  521. finally
  522. {
  523. isManual = !isManual;
  524. }
  525. }
  526. private void Form1_FormClosing(object sender, FormClosingEventArgs e)
  527. {
  528. // 关闭定时器
  529. if (ConnentedTimer.Enabled)
  530. {
  531. ConnentedTimer.Stop();
  532. }
  533. if (timer.Enabled)
  534. {
  535. timer.Stop();
  536. }
  537. // 释放设备
  538. ReleaseCamera();
  539. }
  540. }
  541. }