123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601 |
- using System;
- using System.Collections.Generic;
- using System.Drawing;
- using System.Net;
- using System.Timers;
- using System.Windows.Forms;
- using MvCamCtrl.NET;
- using MvCameraControl;
- namespace CameraModel
- {
- public partial class Form1 : Form
- {
- private const DeviceTLayerType devLayerType = DeviceTLayerType.MvGigEDevice | DeviceTLayerType.MvUsbDevice | DeviceTLayerType.MvGenTLCameraLinkDevice
- | DeviceTLayerType.MvGenTLCXPDevice | DeviceTLayerType.MvGenTLXoFDevice;
- private IDevice _device = null;
- private List<IDeviceInfo> devInfoList = new List<IDeviceInfo>();
- private volatile bool isConnected = false;
- private volatile bool isSuccess = false;
- public delegate void ChangeConnectStatus(bool flag);
- public ChangeConnectStatus changeConnectStatus;
- public delegate void UpdateDevice();
- public UpdateDevice updateDevice;
- private System.Timers.Timer timer;
- private System.Timers.Timer ConnentedTimer;
- private Dictionary<string,string> devices = new Dictionary<string,string>();
- private const string ip = "192.168.1.12";
- private const string subnet = "255.255.255.0";
- private const string gateway = "192.168.1.254";
- public Form1()
- {
- InitializeComponent();
- }
- public bool IsConnected
- {
- set { if (value != isConnected) { isConnected = !isConnected;} changeConnectStatus?.Invoke(isConnected); }
- get { return isConnected; }
- }
- public bool IsSuccess
- {
- set { if (value) { updateDevice.Invoke(); } isSuccess = value; }
- get { return isSuccess; }
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- changeConnectStatus = (flag) => { ConnectStatusChange(flag); };
- updateDevice = () => { updateDeviceSuccess(); };
- // ch: 初始化 SDK | en: Initialize SDK
- //MyCamera.MV_CC_Initialize_NET();
- SDKSystem.Initialize();
- // 初始化定时器
- InitTimer();
- StartTimer();
-
- }
- private void updateDeviceSuccess()
- {
- try
- {
- if (_device != null)
- {
- string UserDefinedName = _device.DeviceInfo.UserDefinedName;
- if (string.IsNullOrEmpty(UserDefinedName))
- {
- AntdUI.Message.success(this, "成功修改型号为:" + UserDefinedName, Font, 10);
- }
- }
- }
- catch (Exception ex)
- {
- LogListBox("查看当前设备型号失败!");
- LogHelper.LoggerMsg(LogLevel.Error, "查看当前设备型号失败:\t" + ex);
- }
- finally
- {
- // 修改完后,相机释放
- ReleaseCamera();
- pictureBox1.Image = global::CameraModel.Properties.Resources.电力_红灯;
- pictureBox2.Image = global::CameraModel.Properties.Resources.电力_红灯;
- cbDeviceList.Items.Clear();
- cbDeviceList.Text = null;
- button_enum.Enabled = true;
- button_connect.Enabled = true;
- button_update.Enabled = false;
- button_clear.Enabled = false;
- if (IsSuccess)
- {
- isSuccess = false;
- }
- IsConnected = false;
- }
- }
- private void StartTimer()
- {
- if(timer == null)
- {
- InitTimer();
- }
- LogListBox("开始检测设备");
- LogHelper.LoggerMsg(LogLevel.Info, "开始检测设备");
- timer.Start();
-
- }
- private void StopTimer()
- {
- if (timer != null)
- {
- LogListBox("停止检测设备");
- LogHelper.LoggerMsg(LogLevel.Info, "停止检测设备");
- timer.Stop();
- }
- }
- private void ConnectStatusChange(bool flag)
- {
- if (flag) // 连接
- {
- // 定时开启检测相机是否还在连接
- if (!ConnentedTimer.Enabled)
- {
- ConnentedTimer.Start();
- }
- LogListBox("设备已连接");
- LogHelper.LoggerMsg(LogLevel.Info, "设备已连接");
- if (timer.Enabled)
- {
- StopTimer();
- }
- button_enum.Enabled = false;
- button_connect.Enabled = false;
- button_update.Enabled = true;
- button_clear.Enabled = true;
- if (_device == null)
- {
- return;
- }
- string ModelName = _device.DeviceInfo.ModelName;
- // 查找型号
- input1.Text = GetDeviceId(ModelName);
- if(!string.IsNullOrEmpty(input1.Text) && input1.Text.Length <= 15)
- {
- // 修改型号
- //DeviceUserID
- _device.Parameters.SetStringValue("DeviceUserID",input1.Text);
- ConnentedTimer.Stop();
- LogListBox("型号修改成功," + cbDeviceList.SelectedValue + "=====>" + input1.Text);
- IsSuccess = true;
- if (!devices.ContainsKey(ModelName))
- {
- devices.Add(ModelName, input1.Text);
- }
- }
- else
- {
- LogListBox("输入型号!!!");
- }
- }
- else //断开
- {
- pictureBox1.Image = global::CameraModel.Properties.Resources.电力_红灯;
- pictureBox2.Image = global::CameraModel.Properties.Resources.电力_红灯;
- LogListBox("设备已断开!!!");
- StartTimer();
- cbDeviceList.Items.Clear();
- cbDeviceList.Text = null;
- button_enum.Enabled = true;
- button_connect.Enabled = true;
- button_update.Enabled = false;
- button_clear.Enabled = false;
-
- }
- }
- private void ReleaseCamera()
- {
- LogListBox("设备资源释放成功");
- LogListBox("===========================================\n");
- //m_MyCamera.MV_CC_CloseDevice_NET();
- //m_MyCamera.MV_CC_DestroyDevice_NET();
- if (_device != null)
- {
- _device.StreamGrabber.StopGrabbing();
- _device.Close();
- _device.Dispose();
- _device = null;
- }
- }
- private string GetDeviceId(string ModelName)
- {
- if (!devices.TryGetValue(ModelName, out string value) && string.IsNullOrEmpty(input1.Text))
- {
- //AntdUI.Input input = new AntdUI.Input() { Size = new Size(300, 80), MaxLength = 15 };
- //if (AntdUI.Modal.open(new AntdUI.Modal.Config(ParentForm, "输入型号", input) { CancelText = null,MaskClosable = false }) == DialogResult.No)
- //{
- // return "";
- //}
- //return input.Text;
- return "";
- }
- if (!string.IsNullOrEmpty(input1.Text))
- {
- return input1.Text;
- }
- return value;
- }
- private void InitTimer()
- {
- if(timer == null)
- {
- timer = new System.Timers.Timer(3000);
- }
- timer.AutoReset = true;
- timer.Elapsed += OnTimerElapsed;
- if (ConnentedTimer == null)
- {
- ConnentedTimer = new System.Timers.Timer(500);
- }
- ConnentedTimer.AutoReset = true;
- ConnentedTimer.Elapsed += OnConnectedTimerElapsed;
- }
- private void OnTimerElapsed(object sender, ElapsedEventArgs e)
- {
- // 检测是否连接
- if (_device != null && _device.IsConnected)
- {
- return;
- }
- if (!IsConnected) // 未连接
- {
- Reconnect();
- }
- }
- private void OnConnectedTimerElapsed(object sender, ElapsedEventArgs e)
- {
- // 检测是否连接
- if (_device == null || !_device.IsConnected)
- {
- IsConnected = false;
- }
- else
- {
- IsConnected = true;
- }
- }
- private void Reconnect()
- {
- if (!IsConnected) // 未连接
- {
- // 检测连接
- if (DeviceListAcq()) // 枚举相机
- {
- if (OpenDevice()) // 打开相机
- {
- IsConnected = true;
-
- }
- }
-
- }
- }
- private bool DeviceListAcq()
- {
- button_update.Enabled = false;
- button_clear.Enabled = false;
- button_connect.Enabled = false;
- devInfoList.Clear();
- cbDeviceList.Items.Clear();
- // ch:枚举设备 | en:Enum device
- int ret = DeviceEnumerator.EnumDevices(devLayerType, out devInfoList);
- if (ret != MvError.MV_OK)
- {
- Console.WriteLine("Enum device failed:{0:x8}", ret);
-
- }
- foreach (IDeviceInfo devInfo in devInfoList)
- {
- cbDeviceList.Items.Add(devInfo.ModelName + ":" + devInfo.UserDefinedName);
- }
- // ch:选择第一项 | en:Select the first item
- if (devInfoList.Count != 0)
- {
-
- if (cbDeviceList.InvokeRequired)
- {
- cbDeviceList.Invoke(new Action(() => {
- cbDeviceList.SelectedIndex = 0;
- cbDeviceList.Text = cbDeviceList.Items[cbDeviceList.SelectedIndex] + "";
- }));
- }
- else
- {
- cbDeviceList.SelectedIndex = 0;
- cbDeviceList.Text = cbDeviceList.Items[cbDeviceList.SelectedIndex] + "";
- }
- pictureBox1.Image = global::CameraModel.Properties.Resources.绿灯;
- button_connect.Enabled = true;
- return true;
- }
- else
- {
- LogListBox("没有检测到相机");
- button_connect.Enabled = false;
- pictureBox1.Image = global::CameraModel.Properties.Resources.电力_红灯;
- pictureBox2.Image = global::CameraModel.Properties.Resources.电力_红灯;
- return false;
- }
- }
- private bool OpenDevice()
- {
- bool is_aotu = false;
- try
- {
- int nRet = -1;
- button_update.Enabled = false;
- button_clear.Enabled = false;
- pictureBox2.Image = global::CameraModel.Properties.Resources.电力_红灯;
- if (devInfoList.Count == 0 || cbDeviceList.SelectedIndex == -1)
- {
- LogListBox("没有检测或选择设备!");
- return false;
- }
- is_aotu = timer.Enabled;
- if (is_aotu)
- {
- timer.Stop();
- }
- // ch:创建设备 | en:Create device
- _device = DeviceFactory.CreateDevice(devInfoList[cbDeviceList.SelectedIndex]);
- IGigEDevice _IGigEDevice = _device as IGigEDevice;
- bool accessible = DeviceEnumerator.IsDeviceAccessible(devInfoList[cbDeviceList.SelectedIndex], DeviceAccessMode.AccessExclusive);
- if (accessible)
- {
- nRet = _IGigEDevice.Open(DeviceAccessMode.AccessControl,0);
- if (MvError.MV_OK != nRet)
- {
- nRet = _IGigEDevice.SetIpConfig(IpConfigType.Static);
- if (nRet != MvError.MV_OK)
- {
- Console.WriteLine("设置静态失败,状态码:" + nRet);
- _IGigEDevice.Dispose();
- return false;
- }
- if (SetIp(_IGigEDevice))
- {
- // 打开并修改
- nRet = _IGigEDevice.Open(DeviceAccessMode.AccessControl, 0);
- if (MvError.MV_OK != nRet)
- {
- //m_MyCamera.MV_CC_DestroyDevice_NET();
- LogHelper.LoggerMsg(LogLevel.Error, "Device open fail! 打开相机状态码:" + nRet);
- LogListBox("Device open fail!");
- _IGigEDevice.Dispose();
- return false;
- }
- }
-
- }
- pictureBox2.Image = global::CameraModel.Properties.Resources.绿灯;
- button_update.Enabled = true;
- button_clear.Enabled = true;
- return true;
- }
- else
- {
- SetIp(_IGigEDevice);
- _IGigEDevice.Dispose();
- IDeviceInfo deviceInfo = devInfoList[cbDeviceList.SelectedIndex];
- IGigEDeviceInfo gigeDevInfo = deviceInfo as IGigEDeviceInfo;
- uint nIp1 = ((gigeDevInfo.NetExport & 0xff000000) >> 24);
- uint nIp2 = ((gigeDevInfo.NetExport & 0x00ff0000) >> 16);
- uint nIp3 = ((gigeDevInfo.NetExport & 0x0000ff00) >> 8);
- uint nIp4 = (gigeDevInfo.NetExport & 0x000000ff);
- string netExportIp = nIp1.ToString() + "." + nIp2.ToString() + "." + nIp3.ToString() + "." + nIp4.ToString();
- //ch:需要重新创建句柄,设置为静态IP方式进行保存 | en: Need to recreate the handle and set it to static IP mode for saving
- //ch: 创建设备 | en: Create device
- _device = DeviceFactory.CreateDeviceByIp(ip, netExportIp);
- if (null == _device)
- {
- LogListBox("Create handle fail");
- return false;
- }
- _IGigEDevice = _device as IGigEDevice;
- nRet = _IGigEDevice.SetIpConfig(IpConfigType.Static);
- if (MvError.MV_OK != nRet)
- {
- LogListBox("Set Ip config fail");
- _IGigEDevice.Dispose();
- _device = null;
- return false;
- }
- }
- return true;
- }
- catch(Exception ex)
- {
- LogListBox("打开设备失败:" + ex.Message);
- LogHelper.LoggerMsg(LogLevel.Error, "打开设备失败:" + ex);
- return false;
- }
- finally
- {
- if (is_aotu)
- {
- timer.Start();
- }
- }
- }
- public uint IpToUint(string ipAddress)
- {
- IPAddress clsIpAddr;
- if (false == IPAddress.TryParse(ipAddress, out clsIpAddr))
- {
- LogListBox("Please enter correct IP");
- return 0;
- }
- return (uint)(IPAddress.NetworkToHostOrder(clsIpAddr.Address) >> 32);
- }
- private bool SetIp(IGigEDevice _IGigEDevice)
- {
-
- uint ipUint = IpToUint(ip);
- uint subnetUint = IpToUint(subnet);
- uint gatewayUint = IpToUint(gateway);
-
- int nRet = _IGigEDevice.ForceIp(ipUint, subnetUint, gatewayUint); // 重置ip后会自动断连
- if (nRet != MvError.MV_OK)
- {
- Console.WriteLine("设置IP失败,状态码:" + nRet);
- _IGigEDevice.Dispose();
- return false;
- }
- return true;
- }
- private void LogListBox(string content)
- {
- DateTime dt = DateTime.Now;
- if (listBox1.InvokeRequired)
- {
- listBox1.Invoke(new Action(() => { listBox1.Items.Insert(0, dt.ToString("HH:mm:ss") + " " + content); listBox1.TopIndex = 0; }));
-
- }
- else
- {
- listBox1.Items.Insert(0, dt.ToString("HH:mm:ss") + " " + content);
- listBox1.TopIndex = 0;
- }
-
- }
- private void button_enum_Click(object sender, EventArgs e)
- {
- DeviceListAcq();
- }
- private void button_connect_Click(object sender, EventArgs e)
- {
- OpenDevice();
- }
- private void button_update_Click(object sender, EventArgs e)
- {
- // 查找型号
- string ModelName = _device.DeviceInfo.ModelName;
- string UserName = GetDeviceId(ModelName);
- if(String.IsNullOrEmpty(UserName) || UserName.Length > 15)
- {
- LogListBox("输入型号!!!");
- return;
- }
- input1.Text = UserName;
- //m_MyCamera.MV_CC_SetDeviceUserID_NET(input1.Text);
- int nRet = _device.Parameters.SetStringValue("DeviceUserID", input1.Text);
- if (nRet != MvError.MV_OK)
- {
- LogListBox("型号修改失败,状态码:" + nRet);
- LogHelper.LoggerMsg(LogLevel.Error, "型号修改失败! 状态码:" + nRet);
- return;
- }
- LogListBox("型号," + cbDeviceList.SelectedValue + "=====>" + _device.DeviceInfo.UserDefinedName);
- ModelName = _device.DeviceInfo.ModelName;
- if (!devices.ContainsKey(ModelName))
- {
- devices.Add(ModelName, input1.Text);
- }
- pictureBox1.Image = global::CameraModel.Properties.Resources.电力_红灯;
- pictureBox2.Image = global::CameraModel.Properties.Resources.电力_红灯;
- if (!DeviceListAcq()) // 枚举相机
- {
- return;
- }
- pictureBox1.Image = global::CameraModel.Properties.Resources.绿灯;
- if (!OpenDevice()) // 打开相机
- {
- return;
- }
- pictureBox2.Image = global::CameraModel.Properties.Resources.绿灯;
- }
- private void button_clear_Click(object sender, EventArgs e)
- {
- //m_MyCamera.MV_CC_SetDeviceUserID_NET("");
- _device.Parameters.SetStringValue("DeviceUserID", "");
- LogListBox("型号清空成功," + cbDeviceList.SelectedValue);
- }
- private bool isManual = false;
- private void button_auto_Click(object sender, EventArgs e)
- {
- try
- {
- button_update.Enabled = false;
- button_clear.Enabled = false;
- pictureBox1.Image = global::CameraModel.Properties.Resources.电力_红灯;
- pictureBox2.Image = global::CameraModel.Properties.Resources.电力_红灯;
- if (!isManual)
- {
- if (timer != null && timer.Enabled)
- {
- timer.Stop();
- }
- if (ConnentedTimer != null && ConnentedTimer.Enabled)
- {
- ConnentedTimer.Stop();
- }
- LogListBox("开启手动模式");
-
- button_auto.Text = "开启自动";
-
- button_auto.DefaultBack = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(152)))), ((int)(((byte)(0)))));
- }
- else
- {
- ReleaseCamera();
- if (timer != null && !timer.Enabled)
- {
- timer.Start();
- }
- LogListBox("开启自动模式");
-
- button_auto.Text = "开启手动";
- button_auto.DefaultBack = System.Drawing.Color.FromArgb(((int)(((byte)(3)))), ((int)(((byte)(169)))), ((int)(((byte)(244)))));
- }
- }
- finally
- {
- isManual = !isManual;
- }
-
- }
- private void Form1_FormClosing(object sender, FormClosingEventArgs e)
- {
- // 关闭定时器
- if (ConnentedTimer.Enabled)
- {
- ConnentedTimer.Stop();
- }
- if (timer.Enabled)
- {
- timer.Stop();
- }
- // 释放设备
- ReleaseCamera();
- }
- }
- }
|