#region CDC Support
public class UsbDeviceMonitor
{
private ManagementEventWatcher plugInWatcher;
private ManagementEventWatcher unPlugWatcher;
private const string MyDeviceDescription = @"My Device Description";
~UsbDeviceMonitor()
{
Dispose();
}
public void Dispose()
{
if (plugInWatcher != null)
try
{
plugInWatcher.Dispose();
plugInWatcher = null;
}
catch (Exception) { }
if (unPlugWatcher == null) return;
try {
unPlugWatcher.Dispose();
unPlugWatcher = null;
}
catch (Exception) { }
}
public void Start()
{
const string plugInSql = "SELECT * FROM __InstanceCreationEvent WITHIN 1 WHERE TargetInstance ISA 'Win32_PnPEntity'";
const string unpluggedSql = "SELECT * FROM __InstanceDeletionEvent WITHIN 1 WHERE TargetInstance ISA 'Win32_PnPEntity'";
var scope = new ManagementScope("root\\CIMV2") { Options = { EnablePrivileges = true } };
var pluggedInQuery = new WqlEventQuery(plugInSql);
plugInWatcher = new ManagementEventWatcher(scope, pluggedInQuery);
plugInWatcher.EventArrived += HandlePluggedInEvent;
plugInWatcher.Start();
var unPluggedQuery = new WqlEventQuery(unpluggedSql);
unPlugWatcher = new ManagementEventWatcher(scope, unPluggedQuery);
unPlugWatcher.EventArrived += HandleUnPluggedEvent;
unPlugWatcher.Start();
}
private void HandleUnPluggedEvent(object sender, EventArrivedEventArgs e)
{
var description = GetDeviceDescription(e.NewEvent);
foreach (COMPortInfo comPort in COMPortInfo.GetCOMPortsInfo())
{
// comboBoxPort.Items.Add(string.Format("{0} – {1}", comPort.Name, comPort.Description));
// this.comboBoxPort.Items.Add(string.Format("{0}", comPort.Description));
}
if (description.Equals(MyDeviceDescription)) {
// Take actions here when the device is unplugged
}
}
private void HandlePluggedInEvent(object sender, EventArrivedEventArgs e)
{
var description = GetDeviceDescription(e.NewEvent);
if (description.Equals(MyDeviceDescription)){
// Take actions here when the device is plugged in
}
}
private static string GetDeviceDescription(ManagementBaseObject newEvent)
{
var targetInstanceData = newEvent.Properties["TargetInstance"];
var targetInstanceObject = (ManagementBaseObject)targetInstanceData.Value;
if (targetInstanceObject == null) return "";
var description = targetInstanceObject.Properties["Description"].Value.ToString();
return description;
}
}
internal class ProcessConnection
{
public static ConnectionOptions ProcessConnectionOptions()
{
ConnectionOptions options = new ConnectionOptions();
options.Impersonation = ImpersonationLevel.Impersonate;
options.Authentication = AuthenticationLevel.Default;
options.EnablePrivileges = true;
return options;
}
public static ManagementScope ConnectionScope(string machineName, ConnectionOptions options, string path)
{
ManagementScope connectScope = new ManagementScope();
connectScope.Path = new ManagementPath(@"\\" + machineName + path);
connectScope.Options = options;
connectScope.Connect();
return connectScope;
}
}
//===================================================
public class COMPortInfo
{
public string Name { get; set; }
public string Description { get; set; }
public COMPortInfo() { }
public static List<COMPortInfo> GetCOMPortsInfo()
{
List<COMPortInfo> comPortInfoList = new List<COMPortInfo>();
ConnectionOptions options = ProcessConnection.ProcessConnectionOptions();
ManagementScope connectionScope = ProcessConnection.ConnectionScope(Environment.MachineName, options, @"\root\CIMV2");
ObjectQuery objectQuery = new ObjectQuery("SELECT * FROM Win32_PnPEntity WHERE ConfigManagerErrorCode = 0");
ManagementObjectSearcher comPortSearcher = new ManagementObjectSearcher(connectionScope, objectQuery);
using (comPortSearcher)
{
string caption = null;
foreach (ManagementObject obj in comPortSearcher.Get())
{
if (obj != null)
{
object captionObj = obj["Caption"];
if (captionObj != null)
{
caption = captionObj.ToString();
if (caption.Contains("(COM"))
{
COMPortInfo comPortInfo = new COMPortInfo();
comPortInfo.Name = caption.Substring(caption.LastIndexOf("(COM")).Replace("(", string.Empty).Replace(")",
string.Empty);
comPortInfo.Description = caption;
comPortInfoList.Add(comPortInfo);
}
}
}
}
}
return comPortInfoList;
}
}
/*********************************************************************
* Base Class
**********************************************************************/
public class MySerialPort : SerialPort
{
private const int DataSize = 256; //
private readonly byte[] _bufer = new byte[DataSize];
private int _stepIndex = 0;
/// </summary>
public MySerialPort()
: base()
{
// Set parameter
base.BaudRate = 115200;
base.DataBits = 8;
base.StopBits = StopBits.One;
base.Parity = Parity.None;
base.ReadTimeout = 1000;
base.DtrEnable = true;
_stepIndex = 0;
if (base.IsOpen)
base.Close();
// Event Data Received;
base.DataReceived += SerialPort_DataReceived;
// Event Error
base.ErrorReceived += SerialPort_ErrorReceived;
}
//===================================================================================
void SerialPort_ErrorReceived(object sender, SerialErrorReceivedEventArgs e)
{
// if(e.EventType == SerialError.TXFull).....
MessageBox.Show("Error recieved: " + e.EventType);
}
// Open Port "com1"
public void Open(string portName)
{
try
{
if (base.IsOpen)
{
base.Close();
}
base.PortName = portName;
base.Open();
base.DiscardInBuffer();
_stepIndex = 0;
}
catch { }
_stepIndex = 0;
}
//------> Out Data <-------
public void Send_CmdData(byte[] buffer)
{
byte CS = 0;
try
{
for (byte i = 0; i < buffer[1] - 1; i++)
CS += buffer[i];
buffer[buffer[1] - 1] = (byte)(~CS + 1);
base.Write(buffer, 0, buffer[1]);
}
catch { }
}
// --Test Input Data
void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
var port = (SerialPort)sender;
try
{
//
int buferSize = port.BytesToRead;
for (int i = 0; i < buferSize; ++i)
{
//
_bufer[_stepIndex++] = (byte)port.ReadByte();
if (_stepIndex == 1)
{
if (0x05 != _bufer[0]) _stepIndex = 0;
else continue;
}
else
if ((_stepIndex >= DataSize) || (_stepIndex == _bufer[1]))
{
byte CS = 0;
for (int j = 0; _stepIndex != 0; _stepIndex--)
CS += _bufer[j++];
if (CS == 0)
{
_stepIndex = 0; // ..
Egor_Host.Egor.CallBackMy.callbackEventHandler(_bufer);
// Egor_Host.FreqStripStatus.Text += "+";
}
}
}
}
catch { }
}
}
#endregion