public HidAttributes GetHidAttributes(SafeFileHandle safeFileHandle) { var isSuccess = HidD_GetAttributes(safeFileHandle, out var hidAttributes); WindowsDeviceBase.HandleError(isSuccess, $"Could not get Hid Attributes (Call {nameof(HidD_GetAttributes)})"); return(hidAttributes); }
public static ConnectedDeviceDefinition GetDeviceDefinition(SafeFileHandle defaultInterfaceHandle, string deviceId) { var deviceDefinition = new ConnectedDeviceDefinition(deviceId) { DeviceType = DeviceType.Usb }; var bufferLength = (uint)Marshal.SizeOf(typeof(USB_DEVICE_DESCRIPTOR)); var isSuccess2 = WinUsbApiCalls.WinUsb_GetDescriptor(defaultInterfaceHandle, WinUsbApiCalls.DEFAULT_DESCRIPTOR_TYPE, 0, WinUsbApiCalls.EnglishLanguageID, out var _UsbDeviceDescriptor, bufferLength, out var lengthTransferred); WindowsDeviceBase.HandleError(isSuccess2, "Couldn't get device descriptor"); if (_UsbDeviceDescriptor.iProduct > 0) { deviceDefinition.ProductName = WinUsbApiCalls.GetDescriptor(defaultInterfaceHandle, _UsbDeviceDescriptor.iProduct, "Couldn't get product name"); } if (_UsbDeviceDescriptor.iSerialNumber > 0) { deviceDefinition.SerialNumber = WinUsbApiCalls.GetDescriptor(defaultInterfaceHandle, _UsbDeviceDescriptor.iSerialNumber, "Couldn't get serial number"); } if (_UsbDeviceDescriptor.iManufacturer > 0) { deviceDefinition.Manufacturer = WinUsbApiCalls.GetDescriptor(defaultInterfaceHandle, _UsbDeviceDescriptor.iManufacturer, "Couldn't get manufacturer"); } deviceDefinition.VendorId = _UsbDeviceDescriptor.idVendor; deviceDefinition.ProductId = _UsbDeviceDescriptor.idProduct; deviceDefinition.WriteBufferSize = _UsbDeviceDescriptor.bMaxPacketSize0; deviceDefinition.ReadBufferSize = _UsbDeviceDescriptor.bMaxPacketSize0; return(deviceDefinition); }
public async Task WriteAsync(byte[] data) { await Task.Run(() => { var isSuccess = WinUsbApiCalls.WinUsb_WritePipe(_SafeFileHandle, WriteEndpoint.PipeId, data, (uint)data.Length, out var bytesWritten, IntPtr.Zero); WindowsDeviceBase.HandleError(isSuccess, "Couldn't write data"); Tracer?.Trace(true, data); }); }
private static string GetHidString(SafeFileHandle safeFileHandle, GetString getString) { var pointerToBuffer = Marshal.AllocHGlobal(126); var isSuccess = getString(safeFileHandle, pointerToBuffer, 126); Marshal.FreeHGlobal(pointerToBuffer); WindowsDeviceBase.HandleError(isSuccess, "Could not get Hid string"); return(Marshal.PtrToStringUni(pointerToBuffer)); }
public static string GetDescriptor(SafeFileHandle defaultInterfaceHandle, byte index, string errorMessage) { var buffer = new byte[256]; var isSuccess = WinUsb_GetDescriptor(defaultInterfaceHandle, USB_STRING_DESCRIPTOR_TYPE, index, EnglishLanguageID, buffer, (uint)buffer.Length, out var transfered); WindowsDeviceBase.HandleError(isSuccess, errorMessage); var descriptor = new string(Encoding.Unicode.GetChars(buffer, 2, (int)transfered)); return(descriptor.Substring(0, descriptor.Length - 1)); }
public async Task <ReadResult> ReadAsync(uint bufferLength) { return(await Task.Run(() => { var bytes = new byte[bufferLength]; var isSuccess = WinUsbApiCalls.WinUsb_ReadPipe(_SafeFileHandle, ReadEndpoint.PipeId, bytes, bufferLength, out var bytesRead, IntPtr.Zero); WindowsDeviceBase.HandleError(isSuccess, "Couldn't read data"); Tracer?.Trace(false, bytes); return new ReadResult(bytes, bytesRead); })); }
public void Dispose() { if (_IsDisposed) { return; } _IsDisposed = true; var isSuccess = WinUsbApiCalls.WinUsb_Free(Handle); WindowsDeviceBase.HandleError(isSuccess, "Interface could not be disposed"); }
public void Dispose() { if (_IsDisposed) { return; } _IsDisposed = true; //This is a native resource, so the IDisposable pattern should probably be implemented... var isSuccess = WinUsbApiCalls.WinUsb_Free(Handle); WindowsDeviceBase.HandleError(isSuccess, "Interface could not be disposed"); }
public HidCollectionCapabilities GetHidCapabilities(SafeFileHandle readSafeFileHandle) { var isSuccess = HidD_GetPreparsedData(readSafeFileHandle, out var pointerToPreParsedData); WindowsDeviceBase.HandleError(isSuccess, "Could not get pre parsed data"); var result = HidP_GetCaps(pointerToPreParsedData, out var hidCollectionCapabilities); if (result != HIDP_STATUS_SUCCESS) { throw new ApiException($"Could not get Hid capabilities. Return code: {result}"); } isSuccess = HidD_FreePreparsedData(ref pointerToPreParsedData); WindowsDeviceBase.HandleError(isSuccess, "Could not release handle for getting Hid capabilities"); return(hidCollectionCapabilities); }
private WindowsUsbInterface GetInterface(SafeFileHandle interfaceHandle) { //TODO: We need to get the read/write size from a different API call... //TODO: Where is the logger/tracer? var isSuccess = WinUsbApiCalls.WinUsb_QueryInterfaceSettings(interfaceHandle, 0, out var interfaceDescriptor); var retVal = new WindowsUsbInterface(interfaceHandle, Logger, Tracer, interfaceDescriptor.bInterfaceNumber, _ReadBufferSize, _WriteBufferSize); WindowsDeviceBase.HandleError(isSuccess, "Couldn't query interface"); for (byte i = 0; i < interfaceDescriptor.bNumEndpoints; i++) { isSuccess = WinUsbApiCalls.WinUsb_QueryPipe(interfaceHandle, 0, i, out var pipeInfo); WindowsDeviceBase.HandleError(isSuccess, "Couldn't query endpoint"); retVal.UsbInterfaceEndpoints.Add(new WindowsUsbInterfaceEndpoint(pipeInfo.PipeId, pipeInfo.PipeType)); } return(retVal); }
private static async Task Go() { var devices = WindowsDeviceBase.GetConnectedDeviceInformations(WindowsDeviceConstants.GUID_DEVINTERFACE_USB_DEVICE); //var device = devices.FirstOrDefault(d => d.DevicePath.ToLower().Contains("2b24")); var device = devices.FirstOrDefault(d => d.DevicePath.ToLower().Contains("1209")); var windowsUsbDevice = new WindowsUsbDevice(device.DevicePath, 64, 64); await windowsUsbDevice.InitializeAsync(); var buffer = new byte[64]; buffer[0] = 0x3f; buffer[1] = 0x23; buffer[2] = 0x23; await windowsUsbDevice.WriteAsync(buffer); var asdasd = await windowsUsbDevice.ReadAsync(); }
private void Initialize() { _ReadSafeFileHandle = ApiService.CreateReadConnection(DeviceId, FileAccessRights.GenericRead | FileAccessRights.GenericWrite); if (_ReadSafeFileHandle.IsInvalid) { return; } var dcb = new Dcb(); var isSuccess = ApiService.AGetCommState(_ReadSafeFileHandle, ref dcb); WindowsDeviceBase.HandleError(isSuccess, Messages.ErrorCouldNotGetCommState); dcb.ByteSize = _ByteSize; dcb.fDtrControl = 1; dcb.BaudRate = (uint)_BaudRate; dcb.fBinary = 1; dcb.fTXContinueOnXoff = 0; dcb.fAbortOnError = 0; dcb.fParity = 1; switch (_Parity) { case Parity.Even: dcb.Parity = 2; break; case Parity.Mark: dcb.Parity = 3; break; case Parity.Odd: dcb.Parity = 1; break; case Parity.Space: dcb.Parity = 4; break; default: dcb.Parity = 0; break; } switch (_StopBits) { case StopBits.One: dcb.StopBits = 0; break; case StopBits.OnePointFive: dcb.StopBits = 1; break; case StopBits.Two: dcb.StopBits = 2; break; default: throw new ArgumentException(Messages.ErrorMessageStopBitsMustBeSpecified); } isSuccess = ApiService.ASetCommState(_ReadSafeFileHandle, ref dcb); WindowsDeviceBase.HandleError(isSuccess, Messages.ErrorCouldNotSetCommState); var timeouts = new CommTimeouts { WriteTotalTimeoutConstant = 0, ReadIntervalTimeout = 1, WriteTotalTimeoutMultiplier = 0, ReadTotalTimeoutMultiplier = 0, ReadTotalTimeoutConstant = 0 }; isSuccess = ApiService.ASetCommTimeouts(_ReadSafeFileHandle, ref timeouts); WindowsDeviceBase.HandleError(isSuccess, Messages.ErrorCouldNotSetCommTimeout); }
private void Initialize() { try { Close(); int errorCode; if (string.IsNullOrEmpty(DeviceId)) { throw new ValidationException($"{nameof(DeviceDefinitionBase)} must be specified before {nameof(InitializeAsync)} can be called."); } _DeviceHandle = APICalls.CreateFile(DeviceId, FileAccessRights.GenericWrite | FileAccessRights.GenericRead, APICalls.FileShareRead | APICalls.FileShareWrite, IntPtr.Zero, APICalls.OpenExisting, APICalls.FileAttributeNormal | APICalls.FileFlagOverlapped, IntPtr.Zero); if (_DeviceHandle.IsInvalid) { //TODO: is error code useful here? errorCode = Marshal.GetLastWin32Error(); if (errorCode > 0) { throw new ApiException($"Device handle no good. Error code: {errorCode}"); } } Logger?.Log(Messages.SuccessMessageGotWriteAndReadHandle, nameof(WindowsUsbInterfaceManager), null, LogLevel.Information); var isSuccess = WinUsbApiCalls.WinUsb_Initialize(_DeviceHandle, out var defaultInterfaceHandle); WindowsDeviceBase.HandleError(isSuccess, Messages.ErrorMessageCouldntIntializeDevice); var connectedDeviceDefinition = WindowsUsbDeviceFactory.GetDeviceDefinition(defaultInterfaceHandle, DeviceId); if (!_WriteBufferSize.HasValue) { if (!connectedDeviceDefinition.WriteBufferSize.HasValue) { throw new ValidationException("Write buffer size not specified"); } _WriteBufferSize = (ushort)connectedDeviceDefinition.WriteBufferSize.Value; } if (!_ReadBufferSize.HasValue) { if (!connectedDeviceDefinition.ReadBufferSize.HasValue) { throw new ValidationException("Read buffer size not specified"); } _ReadBufferSize = (ushort)connectedDeviceDefinition.ReadBufferSize.Value; } //Get the first (default) interface var defaultInterface = GetInterface(defaultInterfaceHandle); UsbInterfaces.Add(defaultInterface); byte i = 0; while (true) { isSuccess = WinUsbApiCalls.WinUsb_GetAssociatedInterface(defaultInterfaceHandle, i, out var interfacePointer); if (!isSuccess) { errorCode = Marshal.GetLastWin32Error(); if (errorCode == APICalls.ERROR_NO_MORE_ITEMS) { break; } throw new ApiException($"Could not enumerate interfaces for device. Error code: { errorCode}"); } var associatedInterface = GetInterface(interfacePointer); //TODO: this is bad design. The handler should be taking care of this UsbInterfaces.Add(associatedInterface); i++; } RegisterDefaultInterfaces(); } catch (Exception ex) { Logger?.Log($"{nameof(Initialize)} error. DeviceId {DeviceId}", nameof(UsbDevice), ex, LogLevel.Error); throw; } }
public void Dispose() { var isSuccess = WinUsbApiCalls.WinUsb_Free(Handle); WindowsDeviceBase.HandleError(isSuccess, "Interface could not be disposed"); }