using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using HidLibrary; namespace UniCOMapp { class USBCOM : IDisposable { private const int VendorId = 0x0461; private const int ProductId = 0x0020; private HidDevice device; private bool attached = false; private bool connectedToDriver = false; private bool disposed = false; public string incomeData; /// /// Occurs when a PowerMate device is attached. /// public event EventHandler DeviceAttached; /// /// Occurs when a PowerMate device is removed. /// public event EventHandler DeviceRemoved; public event EventHandler DataRecieved; /// /// Class constructor. /// public USBCOM() { } /// /// Attempts to connect to a PowerMate device. /// /// After a successful connection, a DeviceAttached event will normally be sent. /// /// True if a PowerMate device is connected, False otherwise. public bool OpenDevice() { device = HidDevices.Enumerate(VendorId, ProductId).FirstOrDefault(); if (device != null) { connectedToDriver = true; device.OpenDevice(); device.Inserted += DeviceAttachedHandler; device.Removed += DeviceRemovedHandler; device.MonitorDeviceEvents = true; device.ReadReport(OnReport); return true; } return false; } /// /// Closes the connection to the device. /// /// FIXME: Verify that this also shuts down any thread waiting for device data. 2012-06-07 thammer. /// public void CloseDevice() { device.CloseDevice(); connectedToDriver = false; } /// /// Closes the connection to the device. /// public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// /// Closes any connected devices. /// /// private void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { CloseDevice(); } disposed = true; } } private void DeviceAttachedHandler() { attached = true; if (DeviceAttached != null) DeviceAttached(this, EventArgs.Empty); device.ReadReport(OnReport); } private void DeviceRemovedHandler() { attached = false; if (DeviceRemoved != null) DeviceRemoved(this, EventArgs.Empty); } private void OnReport(HidReport report) { //if (attached == false) { return; } DataRecieved(this, new EventArgs()); byte[] info = report.Data; string incomeInfo=System.Text.Encoding.UTF8.GetString(info); if(info[0]!=0) { incomeData = incomeInfo; } device.ReadReport(OnReport); } private byte[] PrepareMessage(string message) { byte[] mes1 = System.Text.Encoding.UTF8.GetBytes(message); byte[] result = new byte[mes1.Length + 1]; Array.Copy(mes1, result, mes1.Length); result[result.Length - 1] = 1; return result; } private HidReport ReturnDataToSend(string data) { HidReport repo = new HidReport(1); repo.Data = PrepareMessage(data); return repo; } public void WriteReport(string message) { HidReport rep = ReturnDataToSend(message); device.WriteReport(rep, 5); } } }