public override void Close() { try { write_lock.WaitOne(); if (ep_reader != null) { // detach read event ep_reader.DataReceivedEnabled = false; ep_reader.DataReceived -= (read_usb); } ep_reader = null; ep_writer = null; if (IsOpen()) { // close devices usb_device.Close(); wholeUsbDevice.ReleaseInterface(1); wholeUsbDevice.Close(); } // release devices usb_device = null; wholeUsbDevice = null; UsbDevice.Exit(); } catch (Exception) { // Ignore everything } finally { write_lock.ReleaseMutex(); } }
private static StringBuilder getDescriptorReport(IUsbDevice usbRegistry) { StringBuilder sbReport = new StringBuilder(); if (!usbRegistry.TryOpen()) { return(sbReport); } sbReport.AppendLine(string.Format("{0} OSVersion:{1} LibUsbDotNet Version:{2} DriverMode:{3}", usbRegistry.Info.SerialNumber, Environment.OSVersion, LibUsbDotNetVersion, null)); sbReport.AppendLine(usbRegistry.Info.ToString()); foreach (UsbConfigInfo cfgInfo in usbRegistry.Configs) { sbReport.AppendLine(string.Format("CONFIG #{1}\r\n{0}", cfgInfo.ToString(), cfgInfo.ConfigurationValue)); foreach (UsbInterfaceInfo interfaceInfo in cfgInfo.Interfaces) { sbReport.AppendLine(string.Format("INTERFACE ({1},{2})\r\n{0}", interfaceInfo.ToString(), interfaceInfo.Number, interfaceInfo.AlternateSetting)); foreach (UsbEndpointInfo endpointInfo in interfaceInfo.Endpoints) { sbReport.AppendLine(string.Format("ENDPOINT 0x{1:X2}\r\n{0}", endpointInfo.ToString(), endpointInfo.EndpointAddress)); } } } usbRegistry.Close(); return(sbReport); }
internal void ClosePort() { lock (lock_access) { if (Is_opened) { oldDevice.Enqueue(srb_reader); srb_reader.Flush(); srb_reader.Dispose(); srb_reader = null; oldDevice.Enqueue(srb_writer); srb_writer.Flush(); srb_writer.Dispose(); srb_writer = null; IUsbDevice wholeUsbDevice = selected_device as IUsbDevice; if (!ReferenceEquals(wholeUsbDevice, null)) { // Release interface #0. wholeUsbDevice.ReleaseInterface(0); wholeUsbDevice.ReleaseInterface((1 | 0x80)); wholeUsbDevice.ReleaseInterface(2); wholeUsbDevice.Close(); oldDevice.Enqueue(selected_device); selected_device.Close(); selected_device = null; } } } }
public void OnShutdown() { if (_forwardee != null) { _forwardee.Close(); } }
public void Dispose() { if (monitorBuddyDevice != null) { monitorBuddyDevice.ReleaseInterface(interfaceID); monitorBuddyDevice.Close(); } }
/// <summary> /// Close and open the device /// </summary> /// <param name="device">The device</param> private static void CloseAndOpen(IUsbDevice device) { if (device.IsOpen) { device.Close(); } Initialize((UsbDevice)device); }
/// <summary> /// Cleans up a device, releasing interfaces and closing connection /// </summary> /// <param name="device">The device to close</param> private void Destroy(IUsbDevice device) { try { // Attempt to clean up device device.ReleaseInterface(device.Configs[0].Interfaces[0].Number); device.Close(); } catch (Exception e) { _logger.LogWarning(e, "Attempted to clean up device, but failed."); } }
private void addDevice(IUsbDevice deviceReg, string display) { if (!deviceReg.TryOpen()) { return; } mUsbRegistry = deviceReg; TreeNode tvDevice = tvInfo.Nodes.Add(display); string[] sDeviceAdd = mUsbDevice.Info.ToString().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); foreach (string s in sDeviceAdd) { tvDevice.Nodes.Add(s); } foreach (UsbConfigInfo cfgInfo in mUsbDevice.Configs) { TreeNode tvConfig = tvDevice.Nodes.Add("Config " + cfgInfo.ConfigurationValue); string[] sCfgAdd = cfgInfo.ToString().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); foreach (string s in sCfgAdd) { tvConfig.Nodes.Add(s); } TreeNode tvInterfaces = tvConfig; //.Nodes.Add("Interfaces"); foreach (UsbInterfaceInfo interfaceInfo in cfgInfo.Interfaces) { TreeNode tvInterface = tvInterfaces.Nodes.Add("Interface [" + interfaceInfo.Number + "," + interfaceInfo.AlternateSetting + "]"); string[] sInterfaceAdd = interfaceInfo.ToString().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); foreach (string s in sInterfaceAdd) { tvInterface.Nodes.Add(s); } TreeNode tvEndpoints = tvInterface; //.Nodes.Add("Endpoints"); foreach (UsbEndpointInfo endpointInfo in interfaceInfo.Endpoints) { TreeNode tvEndpoint = tvEndpoints.Nodes.Add("Endpoint 0x" + (endpointInfo.EndpointAddress).ToString("X2")); string[] sEndpointAdd = endpointInfo.ToString().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); foreach (string s in sEndpointAdd) { tvEndpoint.Nodes.Add(s); } } } } mUsbDevice.Close(); }
public void Close() { if (Driver.IsOpen) { IUsbDevice wholeUsbDevice = Driver as IUsbDevice; if (wholeUsbDevice is not null) { // Release interface #0. wholeUsbDevice.ReleaseInterface(0); } Driver.Close(); } DeviceInfo.Ready = Driver.IsOpen; }
public static void MarkInterfaceClosed() { lock (device) { refCount--; if (refCount == 0) { device.Close(); } else if (refCount < 0) { throw new Exception("interface refCount out of range"); } } }
public void killReceiver() { // Loop through each Controller to clean it up for (int i = 0; i < 4; i++) { // Turns off the Xbox controllers if (receiverAttached) { if (xboxControllers[i].controllerAttached) { // Clean up the controller's keep-alive threads xboxControllers[i].killKeepAlive(); // Clean up the controller's mouse mode threads xboxControllers[i].killMouseMode(); // Clean up the controller's button combo threads xboxControllers[i].killButtonCombo(); // Clean up the controller xboxControllers[i].killController(); } } // Cleans up the Wireless Receiver Data if (epWriters[i] != null) { epWriters[i].Abort(); epWriters[i].Dispose(); } if (epReaders[i] != null) { epReaders[i].Abort(); epReaders[i].Dispose(); } } // Clean up the Receiver if (wirelessReceiver != null) { if (receiverAttached) { wirelessReceiver.Close(); } wirelessReceiver = null; } }
public void Dispose() { aliveTimer.Change(Timeout.Infinite, Timeout.Infinite); reader.Dispose(); writer.Dispose(); try { dev.Close(); } catch { } dev = null; SensorDataUpdate = null; Removed = null; }
public override void Close() { if (_reader is object) { _reader.Dispose(); } if (_writer is object) { _writer.Dispose(); } if (_dev is object) { _dev.ReleaseInterface(0); _dev.Close(); _dev = null; } }
public void Dispose() { try { if (_refreshSlotsThread != null) { _refreshSlotsThread.Abort(); _refreshSlotsThread = null; } if (_slots != null) { foreach (var slot in _slots.Values) { if (slot != null) { slot.DataReader.DataReceivedEnabled = false; slot.DataReader.DataReceived -= DataReader_DataReceived; slot.DataReader.Abort(); slot.DataReader.Dispose(); slot.HeadsetReader.DataReceivedEnabled = false; slot.HeadsetReader.DataReceived -= HeadsetReader_DataReceived; slot.HeadsetReader.Abort(); slot.HeadsetReader.Dispose(); } } } _slots = new Dictionary <int, ReceiverSlot>(); if (_device != null) { if (_device.IsOpen) { _device.Close(); } _device = null; } } catch { //Don't care... } }
public void Close() { if (_messageThread != null) { try { _messageThread.Abort(); } catch { /* Don't care...*/ }; _messageThread = null; } try { if (_device != null && _device.IsOpen) { _device.Close(); } } catch { //Don't care... } }
private bool reconnect() { //clear the info so far if (MyUsbDevice != null) { writer.Dispose(); wholeUsbDevice.ReleaseInterface(0); wholeUsbDevice.Close(); MyUsbDevice.Close(); UsbDevice.Exit(); } //now start over MyUsbFinder = new UsbDeviceFinder(0x06D3, 0x01D0); MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder); // If the device is open and ready if (MyUsbDevice == null) { msgchnl.setcurrMessage("Problem in reconnect() MyUsbDevice is null"); return(false); } else { wholeUsbDevice = MyUsbDevice as IUsbDevice; if (!ReferenceEquals(wholeUsbDevice, null)) { // Select config #1 wholeUsbDevice.SetConfiguration(1); // Claim interface #0. wholeUsbDevice.ClaimInterface(0); } writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep02); reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01); //Console.WriteLine("New Writer an reader was assigned"); return(true); } }
public static void Main(string[] args) { var ec = Error.Success; using (var context = new UsbContext()) { try { // Find and open the usb device. MyUsbDevice = context.Find(MyUsbFinder); // If the device is open and ready if (MyUsbDevice == null) { throw new Exception("Device Not Found."); } // If this is a "whole" usb device (libusb-win32, linux libusb) // it will have an IUsbDevice interface. If not (WinUSB) the // variable will be null indicating this is an interface of a // device. var wholeUsbDevice = MyUsbDevice as IUsbDevice; if (!ReferenceEquals(wholeUsbDevice, null)) { // This is a "whole" USB device. Before it can be used, // the desired configuration and interface must be selected. // Select config #1 wholeUsbDevice.SetConfiguration(1); // Claim interface #0. wholeUsbDevice.ClaimInterface(0); } // open read endpoint 1. var reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01); // open write endpoint 1. var writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep01); // Remove the exepath/startup filename text from the begining of the CommandLine. var cmdLine = Regex.Replace( Environment.CommandLine, "^\".+?\"^.*? |^.*? ", "", RegexOptions.Singleline); if (!string.IsNullOrEmpty(cmdLine)) { ec = writer.Write(Encoding.Default.GetBytes(cmdLine), 2000, out var bytesWritten); if (ec != Error.Success) { throw new Exception($"The command line {cmdLine} failed with an error of {ec}."); } var readBuffer = new byte[1024]; while (ec == Error.Success) { // If the device hasn't sent data in the last 100 milliseconds, // a timeout error (ec = IoTimedOut) will occur. ec = reader.Read(readBuffer, 100, out var bytesRead); if (bytesRead == 0) { throw new Exception("No more bytes!"); } // Write that output to the console. Console.Write(Encoding.Default.GetString(readBuffer, 0, bytesRead)); } Console.WriteLine("\r\nDone!\r\n"); } else { throw new Exception("Nothing to do."); } } catch (Exception ex) { Console.WriteLine(); Console.WriteLine((ec != Error.Success ? ec + ":" : string.Empty) + ex.Message); } finally { if (MyUsbDevice != null) { if (MyUsbDevice.IsOpen) { // If this is a "whole" usb device (libusb-win32, linux libusb-1.0) // it exposes an IUsbDevice interface. If not (WinUSB) the // 'wholeUsbDevice' variable will be null indicating this is // an interface of a device; it does not require or support // configuration and interface selection. var wholeUsbDevice = MyUsbDevice as IUsbDevice; if (!ReferenceEquals(wholeUsbDevice, null)) { // Release interface #0. wholeUsbDevice.ReleaseInterface(0); } MyUsbDevice.Close(); } MyUsbDevice = null; } // Wait for user input.. Console.ReadKey(); } } }
public static void Main(string[] args) { Error ec = Error.Success; using (UsbContext context = new UsbContext()) { try { // Find and open the usb device. MyUsbDevice = context.Find(MyUsbFinder); // If the device is open and ready if (MyUsbDevice == null) { throw new Exception("Device Not Found."); } // If this is a "whole" usb device (libusb-win32, linux libusb-1.0) // it exposes an IUsbDevice interface. If not (WinUSB) the // 'wholeUsbDevice' variable will be null indicating this is // an interface of a device; it does not require or support // configuration and interface selection. IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice; if (!ReferenceEquals(wholeUsbDevice, null)) { // This is a "whole" USB device. Before it can be used, // the desired configuration and interface must be selected. // Select config #1 wholeUsbDevice.SetConfiguration(1); // Claim interface #0. wholeUsbDevice.ClaimInterface(0); } // open read endpoint 1. var reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01); byte[] readBuffer = new byte[1024]; while (ec == Error.Success) { int bytesRead; // If the device hasn't sent data in the last 5 seconds, // a timeout error (ec = IoTimedOut) will occur. ec = reader.Read(readBuffer, 5000, out bytesRead); if (bytesRead == 0) { throw new Exception(string.Format("{0}:No more bytes!", ec)); } Console.WriteLine("{0} bytes read", bytesRead); // Write that output to the console. Console.Write(Encoding.Default.GetString(readBuffer, 0, bytesRead)); } Console.WriteLine("\r\nDone!\r\n"); } catch (Exception ex) { Console.WriteLine(); Console.WriteLine((ec != Error.Success ? ec + ":" : String.Empty) + ex.Message); } finally { if (MyUsbDevice != null) { if (MyUsbDevice.IsOpen) { // If this is a "whole" usb device (libusb-win32, linux libusb-1.0) // it exposes an IUsbDevice interface. If not (WinUSB) the // 'wholeUsbDevice' variable will be null indicating this is // an interface of a device; it does not require or support // configuration and interface selection. IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice; if (!ReferenceEquals(wholeUsbDevice, null)) { // Release interface #0. wholeUsbDevice.ReleaseInterface(0); } MyUsbDevice.Close(); } MyUsbDevice = null; } // Wait for user input.. Console.ReadKey(); } } }
public void Close() { _device.Close(); }
public void Cleanup() { dev.ReleaseInterface(0); dev.Close(); dev = null; }
/// <summary> /// Closes the USB connection to the DAC. This object will no longer be usable and if the DAC is needed again you must search for it via HeliosController.OpenDevices() once more. /// </summary> public void Close() { usbDevice.Close(); }
public static void Main(string[] args) { Error ec = Error.Success; using (UsbContext context = new UsbContext()) { try { // Find and open the usb device. MyUsbDevice = context.Find(MyUsbFinder); // If the device is open and ready if (MyUsbDevice == null) { throw new Exception("Device Not Found."); } // If this is a "whole" usb device (libusb-win32, linux libusb) // it will have an IUsbDevice interface. If not (WinUSB) the // variable will be null indicating this is an interface of a // device. IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice; if (!ReferenceEquals(wholeUsbDevice, null)) { // This is a "whole" USB device. Before it can be used, // the desired configuration and interface must be selected. // Select config #1 wholeUsbDevice.SetConfiguration(1); // Claim interface #0. wholeUsbDevice.ClaimInterface(0); } // open read endpoint 1. var reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01); // open write endpoint 1. var writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep01); // the write test data. string testWriteString = "ABCDEFGH"; Error ecWrite; Error ecRead; int transferredOut; int transferredIn; UsbTransfer usbWriteTransfer; UsbTransfer usbReadTransfer; byte[] bytesToSend = Encoding.Default.GetBytes(testWriteString); byte[] readBuffer = new byte[1024]; int testCount = 0; do { // Create and submit transfer ecRead = reader.SubmitAsyncTransfer(readBuffer, 0, readBuffer.Length, 100, out usbReadTransfer); if (ecRead != Error.Success) { throw new Exception("Submit Async Read Failed."); } ecWrite = writer.SubmitAsyncTransfer(bytesToSend, 0, bytesToSend.Length, 100, out usbWriteTransfer); if (ecWrite != Error.Success) { usbReadTransfer.Dispose(); throw new Exception("Submit Async Write Failed."); } WaitHandle.WaitAll(new WaitHandle[] { usbWriteTransfer.AsyncWaitHandle, usbReadTransfer.AsyncWaitHandle }, 200, false); if (!usbWriteTransfer.IsCompleted) { usbWriteTransfer.Cancel(); } if (!usbReadTransfer.IsCompleted) { usbReadTransfer.Cancel(); } ecWrite = usbWriteTransfer.Wait(out transferredOut); ecRead = usbReadTransfer.Wait(out transferredIn); usbWriteTransfer.Dispose(); usbReadTransfer.Dispose(); Console.WriteLine("Read :{0} Error:{1}", transferredIn, ecRead); Console.WriteLine("Write :{0} Error:{1}", transferredOut, ecWrite); Console.WriteLine("Data :" + Encoding.Default.GetString(readBuffer, 0, transferredIn)); testCount++; } while (testCount < 5); Console.WriteLine("\r\nDone!\r\n"); } catch (Exception ex) { Console.WriteLine(); Console.WriteLine((ec != Error.Success ? ec + ":" : String.Empty) + ex.Message); } finally { if (MyUsbDevice != null) { if (MyUsbDevice.IsOpen) { // If this is a "whole" usb device (libusb-win32, linux libusb-1.0) // it exposes an IUsbDevice interface. If not (WinUSB) the // 'wholeUsbDevice' variable will be null indicating this is // an interface of a device; it does not require or support // configuration and interface selection. IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice; if (!ReferenceEquals(wholeUsbDevice, null)) { // Release interface #0. wholeUsbDevice.ReleaseInterface(0); } MyUsbDevice.Close(); } MyUsbDevice = null; } // Wait for user input.. Console.ReadKey(); } } }
public async Task MonitorEndpoint() { await Task.Run(async() => { using (var context = new UsbContext()) { byte[] endpointBufferTmp = new byte[endpointBufferSize]; while (monitoring) { try { if (device is null || !device.IsOpen) { bool deviceFound = await GetDevice(context); if (deviceFound) { OnUSBConnectedEvent(true); } else { OnUSBConnectedEvent(false); continue; } } int bytesRead = 0; var result = endpointReader.Read(endpointBufferTmp, 100, out bytesRead); if (result == LibUsbDotNet.Error.Success) { if (!endpointBufferTmp.SequenceEqual(endpointBuffer)) { // todo make this button push check more legible/general if (endpointBufferTmp[0] != endpointBuffer[0] && endpointBufferTmp[0] != 0) { OnButtonPressed(ButtonOnePressed); } if (endpointBufferTmp[1] != endpointBuffer[1] && endpointBufferTmp[1] != 0) { OnButtonPressed(ButtonTwoPressed); } if (endpointBufferTmp[2] != endpointBuffer[2] && endpointBufferTmp[2] != 0) { OnButtonPressed(DialButtonPressed); } if (endpointBufferTmp[3] != endpointBuffer[3]) { var currentDialValue = BitConverter.ToInt32(endpointBuffer, 3); var newDialValue = BitConverter.ToInt32(endpointBufferTmp, 3); var dialDiff = newDialValue - currentDialValue; OnDialChanged(new DialRotationEventArgs() { dialChange = dialDiff }); } // save state endpointBufferTmp.CopyTo(endpointBuffer, 0); } } } catch (Exception e) { OnUSBConnectedEvent(false); if (device != null) { device.Close(); } } } } }); }