//Open the virtual bus driver async Task <bool> OpenVirtualBusDriver() { try { vVirtualBusDevice = new WinUsbDevice(GuidClassVigemVirtualBus, string.Empty, false, false); if (vVirtualBusDevice.Connected) { Debug.WriteLine("Virtual bus driver is installed."); vVirtualBusDevice.VirtualUnplugAll(); await Task.Delay(500); return(true); } else { Debug.WriteLine("Virtual bus driver not installed."); return(false); } } catch { Debug.WriteLine("Failed to open virtual bus driver."); return(false); } }
private bool OpenCustomDevice(out WinUsbDevice usb, out UsbEndpointReader reader, out UsbEndpointWriter writer) { usb = null; reader = null; writer = null; var device = UsbDevice.AllWinUsbDevices.FirstOrDefault(d => d.Vid == 0x1974 && d.Pid == 0x0001) as WinUsbRegistry; if (device != null) { if (device.Open(out usb)) { writer = usb.OpenEndpointWriter(WriteEndpointID.Ep01); writer.Reset(); writer.Flush(); reader = usb.OpenEndpointReader(ReadEndpointID.Ep01); reader.Reset(); reader.Flush(); reader.ReadBufferSize = 32; reader.DataReceived += CustomDataReceived; reader.DataReceivedEnabled = true; return(true); } } return(false); }
private unsafe IAsyncResult BeginWriteCore(byte[] array, int offset, int count, AsyncCallback userCallback, Object stateObject) { Debug.Assert(userCallback == null); Debug.Assert(stateObject == null); CheckParametersForBegin(array, offset, count); AsyncFileStream_AsyncResult asyncResult = new AsyncFileStream_AsyncResult(userCallback, stateObject, true); if (count == 0) { asyncResult.SignalCompleted(); } else { // Keep the array in one location in memory until the OS writes the // relevant data into the array. Free GCHandle later. asyncResult.PinBuffer(array); fixed(byte *p = array) { uint numBytesWritten = 0; bool res; byte[] byteArray = new byte[count]; Marshal.Copy(new IntPtr(p + offset), byteArray, 0, count); //res = Native.ReadFile(m_handle.DangerousGetHandle(), p + offset, count, out numBytesRead, asyncResult.OverlappedPtr); res = WinUsbDevice.WinUsb_WritePipe( m_winUsbDevice.DeviceInfo.winUsbHandle, System.Convert.ToByte(m_winUsbDevice.DeviceInfo.bulkOutPipe), byteArray, (uint)count, ref numBytesWritten, System.IntPtr.Zero); if (res == false) { if (HandleErrorSituation("BeginWrite", true)) { asyncResult.SignalCompleted(); } else { m_outstandingRequests.Add(asyncResult); } } else { asyncResult.m_numBytes = (int)numBytesWritten; asyncResult.SignalCompleted(); } } } return(asyncResult); }
internal static void ForceDisconnect() { _usbDevice.Disconnected = true; DeviceDetected = false; _usbDevice = new WinUsbDevice(); _deviceManager = new DeviceManagement(); _devicePathName = string.Empty; }
//public const int IOCTL_WINUSB_MANUFACTURER = 2; //public const int IOCTL_WINUSB_PRODUCT = 3; //public const int IOCTL_WINUSB_SERIAL_NUMBER = 4; //public const int IOCTL_WINUSB_VENDOR_ID = 5; //public const int IOCTL_WINUSB_PRODUCT_ID = 6; //public const int IOCTL_WINUSB_DISPLAY_NAME = 7; //public const int IOCTL_WINUSB_PORT_NAME = 8; //--// public WinUsb_AsyncUsbStream(string port) : base(port) { m_winUsbDevice = new WinUsbDevice(); m_winUsbDevice.DeviceInfo.deviceHandle = (Microsoft.Win32.SafeHandles.SafeFileHandle)m_handle; if (!m_winUsbDevice.InitializeDevice()) { throw new ArgumentException(); } s_textProperties[DeviceHash] = IOCTL_WINUSB_DEVICE_HASH; }
/// <summary> /// The guid and the form that will utilize the mechaboard will be passed as /// arguments to the constructor /// In the context of our final project, the form reference that will /// be passed to the constructor is the /// reference for the mainform only. Other forms will subscribe and /// unsubscribe to/from device notifications via /// the methods of the MechaBoard class. Note that form reference is passed solely for subscribing /// </summary> /// <param name="guid">the unique identifier string for the mechaboard that is to be used</param> /// <param name="form_reference">the form that is going to utilize the functionalities /// of the mechaboar</param> public MechaBoard(String guid, Form form_reference) { //notification handle for the main board deviceNotificationHandle = IntPtr.Zero; //device for usb communication device = new WinUsbDevice(); //manager for the device deviceManager = new DeviceManagement(); //path name of the device used for identification devicePathName = ""; //whether device detected or not isDeviceDetected = false; //guid of the device deviceGUID = guid; //form reference used to register the notifications about the board, should be the //reference of the mainform formReference = form_reference; //lock handle to safely provide accesses to the board boardLockHandle = new object(); }
private void CloseCustomDevice(ref WinUsbDevice usb, ref UsbEndpointReader reader, ref UsbEndpointWriter writer) { if (reader != null) { reader.DataReceivedEnabled = false; reader.DataReceived -= CustomDataReceived; reader.Dispose(); } reader = null; if (writer != null) { writer.Dispose(); } writer = null; if (usb != null) { usb.Close(); } usb = null; }
public USB() { WinUsbDevice.OpenUsbDevice(ref guid, out MyUsbDevice); async_read_t = new Thread(async_read); if (MyUsbDevice.Info.ManufacturerString != "Nerox") { throw new Exception("Device Not Found."); } if (MyUsbDevice.Info.ProductString != "Nerox USB Controller") { throw new Exception("Device Not Found."); } // If the device is open and ready if (MyUsbDevice == null) { throw new Exception("Device Not Found."); } async_read_t.Start(); }
//Reset controller status to defaults public void ResetControllerStatus() { try { Debug.WriteLine("Reset the controller status for controller: " + NumberId); //Controller Status Activated = false; //Battery Status BatteryCurrent = new ControllerBattery(); BatteryPrevious = new ControllerBattery(); //Time Variables PrevInputTicks = 0; LastInputTicks = 0; LastActiveTicks = 0; //Controller Details Details = null; BlockOutput = false; //Controller Tasks InputVirtualOverlapped = new NativeOverlapped() { EventHandle = CreateEvent(IntPtr.Zero, true, false, null) }; OutputVirtualOverlapped = new NativeOverlapped() { EventHandle = CreateEvent(IntPtr.Zero, true, false, null) }; InputControllerTask = new AVTaskDetails(); OutputControllerTask = new AVTaskDetails(); OutputVirtualTask = new AVTaskDetails(); OutputGyroTask = new AVTaskDetails(); //WinUsb Device Variables WinUsbDevice = null; //Hid Device Variables HidDevice = null; //Gyro Dsu Client Variables GyroDsuClientPacketNumber = 0; GyroDsuClientEndPoint = null; //Device In and Output InputButtonCountLoop1 = 0; InputButtonCountTotal1 = 80; InputButtonCountLoop2 = 0; InputButtonCountTotal2 = 80; InputButtonCountLoop3 = 0; InputButtonCountTotal3 = 80; InputHeaderOffsetFinished = false; InputHeaderOffsetByte = 0; InputButtonOffsetFinished = false; InputButtonOffsetByte = 0; InputReport = null; OutputReport = null; XInputData = new XUSB_INPUT_REPORT(); XOutputData = new XUSB_OUTPUT_REPORT(); XOutputCurrentRumbleHeavy = 0; XOutputCurrentRumbleLight = 0; XOutputPreviousRumbleHeavy = 0; XOutputPreviousRumbleLight = 0; //Controller Input InputCurrent = new ControllerInput(); SupportedCurrent = new ControllerSupported(); } catch { } }
private void EnableCustomHMD(bool en) { if (en && CustomHMDThread == null) { CustomHMDThread = new Thread(() => { List <byte[]> outgoingPackets = null; var lastOutgoing = DateTime.MinValue; WinUsbDevice _usb = null; UsbEndpointWriter _writer = null; UsbEndpointReader _reader = null; var data = new byte[32]; while (CustomHMDThread != null) { SetState(CommState.DriverActive, _sharedMem.IsDriverActive); if (_usb == null) { OpenCustomDevice(out _usb, out _reader, out _writer); if (_usb != null) { SetState(CommState.TrackerActive, true); } else { SetState(CommState.TrackerActive, false); Thread.Sleep(10); } } try { outgoingPackets = _sharedMem.ReadOutgoingPackets(); if (outgoingPackets != null) { lock (OutgoingPackets) { foreach (var item in outgoingPackets) { OutgoingPackets.Enqueue(item); } } } //empty output even if no usb connected lock (OutgoingPackets) { if (OutgoingPackets.Count > 0 && (DateTime.Now - lastOutgoing).TotalMilliseconds >= 100) { lastOutgoing = DateTime.Now; var d = OutgoingPackets.Dequeue(); //33 byte packets in queue if (_writer != null) { int len; var err = _writer.Write(d, 100, out len); //send before monitor process if (err != ErrorCode.Ok) { throw new Exception(UsbDevice.LastErrorString); } } if (IsDebug && IsVisible) { var packet = StructFromBytes <USBPacket>(d); packet.ParseFields(); lock (OutPacketMonitor) OutPacketMonitor.Add(packet); } } } } catch (Exception ex) { Debug.WriteLine(ex.Message); CloseCustomDevice(ref _usb, ref _reader, ref _writer); Thread.Sleep(100); } } CloseCustomDevice(ref _usb, ref _reader, ref _writer); SetState(CommState.TrackerActive, false); UsbDevice.Exit(); }); CustomHMDThread.Start(); } else if (!en && CustomHMDThread != null) { var t = CustomHMDThread; CustomHMDThread = null; t.Join(); SetState(CommState.TrackerActive, false); } }
//--// //--// //--// private unsafe IAsyncResult BeginReadCore(byte[] array, int offset, int count, AsyncCallback userCallback, Object stateObject) { Debug.Assert(userCallback == null); Debug.Assert(stateObject == null); CheckParametersForBegin(array, offset, count); AsyncFileStream_AsyncResult asyncResult = new AsyncFileStream_AsyncResult(userCallback, stateObject, false); if (count == 0) { asyncResult.SignalCompleted(); } else { // Keep the array in one location in memory until the OS writes the // relevant data into the array. Free GCHandle later. asyncResult.PinBuffer(array); int totalRead = 0; int availableToTransfer = 0; fixed(byte *dst = array) { // if we already have available data, then we need to use it lock (syncRW) { System.Diagnostics.Debug.Assert(count == m_bytesAvailable); if (m_bytesAvailable > 0) { // truncate availableToTransfer = Math.Min(count, (int)m_bytesAvailable); // copy over to the application buffer Marshal.Copy(m_buffer, 0, new IntPtr(dst + offset), availableToTransfer); // update the available bytes count m_bytesAvailable -= (uint)availableToTransfer; totalRead += availableToTransfer; // adjust the buffering if there is a left over // this will never happen if application call AvailableBytes and the reads them if (m_bytesAvailable > 0) { fixed(byte *copy = m_buffer) { Marshal.Copy(new IntPtr(copy), m_buffer, (int)availableToTransfer, (int)m_bytesAvailable); } } } } // if we need to read more, then we shoudl go to the stream directly int remainder = count - availableToTransfer; if (remainder > 0) { byte[] byteArray = new byte[remainder]; Array.Clear(byteArray, 0, byteArray.Length); fixed(byte *p = byteArray) { uint numBytesRead = 0; bool res; res = WinUsbDevice.WinUsb_ReadPipe( m_winUsbDevice.DeviceInfo.winUsbHandle, System.Convert.ToByte(m_winUsbDevice.DeviceInfo.bulkInPipe), byteArray, (uint)remainder, ref numBytesRead, System.IntPtr.Zero); if (res == false) { if (HandleErrorSituation("BeginRead", false)) { asyncResult.SignalCompleted(); } else { m_outstandingRequests.Add(asyncResult); } } else { Marshal.Copy(byteArray, 0, new IntPtr(dst + totalRead + offset), (int)numBytesRead); totalRead += (int)numBytesRead; } } } if (totalRead > 0) { asyncResult.m_numBytes = (int)totalRead; asyncResult.SignalCompleted(); } } } return(asyncResult); }