public bool TurnOffLight(LightColour colour) { var modifiedColour = (short)colour * 0x100; var packet = new UsbSetupPacket(0x48, 0x12, (short)0x0c0a, (short)modifiedColour, (short)0x0000); int temp2; return MyUsbDevice.ControlTransfer(ref packet, new byte[0], 0, out temp2); }
private int SendControlTransfer(byte[] buffer, byte request, short value, short index, short outLength) { LibUsbDotNet.Main.UsbSetupPacket setupPacket = new LibUsbDotNet.Main.UsbSetupPacket((byte)UsbRequestType.TypeVendor | BM_REQUEST_DEVICE_TO_HOST, request, value, index, outLength); int bytesRead = 0; dev.ControlTransfer(ref setupPacket, buffer, 8, out bytesRead); return(bytesRead); }
public override bool ControlTransfer(SafeHandle InterfaceHandle, UsbSetupPacket SetupPacket, IntPtr Buffer, int BufferLength, out int LengthTransferred) { return WinUsb_ControlTransfer(InterfaceHandle, SetupPacket, Buffer, BufferLength, out LengthTransferred, IntPtr.Zero); }
/// <summary> /// Read analog voltage from a spesific channel /// </summary> /// <param name="channel">0 for RESET pin, 1 for SCK pin, 2 for internal Temperature sensor</param> /// <returns>Analog voltage in 10bit resoultion</returns> public ushort analogRead(byte channel) { byte[] buffer_ = new byte[8]; int whatIsThis = 8; MySetupPacket = new UsbSetupPacket(0xC0, 15, channel, 0, 8); MyUsbDevice.ControlTransfer(ref MySetupPacket, buffer_, 8, out whatIsThis); return (ushort)((buffer_[1] <<8) + (buffer_[0])); }
/// <summary> /// Always returns 0x22 (34) so far /// </summary> /// <returns></returns> public ushort GetInitStatus() { UsbSetupPacket setup = new UsbSetupPacket(0xC0, 0x10, 0x0, 0x0, 0x1); int len = 0; byte[] buf = new byte[1]; MyUsbDevice.ControlTransfer(ref setup, buf, (ushort)buf.Length, out len); return buf[0]; }
public void SetTilt(sbyte tiltValue) { if (!MyUsbDevice.IsOpen) { InitDevice(); } ushort mappedValue = (ushort)(0xff00 | (byte)tiltValue); UsbSetupPacket setup = new UsbSetupPacket(0x40, 0x31, mappedValue, 0x0, 0x0); int len = 0; MyUsbDevice.ControlTransfer(ref setup, IntPtr.Zero, 0, out len); }
public override bool ControlTransfer(SafeHandle interfaceHandle, UsbSetupPacket setupPacket, IntPtr buffer, int bufferLength, out int lengthTransferred) { return LibUsbDriverIO.ControlTransfer(interfaceHandle, setupPacket, buffer, bufferLength, out lengthTransferred, UsbConstants.DEFAULT_TIMEOUT); }
public unsafe override void GetFeature(byte[] buffer, int offset, int count) { Throw.If.OutOfRange(buffer, offset, count); try { UsbSetupPacket packet = new UsbSetupPacket (0x80 | 0x20, buffer[offset], (short)0x1, 0, 33); int transferred; _device.ControlTransfer (ref packet, buffer, count, out transferred); } finally { } }
private void ClearStatus() //throws Exception { //int length = usb.controlTransfer(DFU_RequestType, DFU_CLRSTATUS, 0, 0, null, 0, 0); LibUsbDotNet.Main.UsbSetupPacket setup = new LibUsbDotNet.Main.UsbSetupPacket() { RequestType = (byte)(DFU_RequestType), Request = (byte)DFU_CLRSTATUS, Value = 0, Index = 0 }; int length = usb.ControlTransfer(setup, null, 0, 0); if (length < 0) { throw new Exception("USB Failed during clearStatus"); } }
//public int controlTransfer (int requestType, int request, int value, int index, byte[] buffer, int length, int timeout) //Performs a control transaction on endpoint zero for this device.The direction of the transfer is determined by the request type.If requestType & USB_ENDPOINT_DIR_MASK is USB_DIR_OUT, then the transfer is a write, and if it is USB_DIR_IN, then the transfer is a read. //This method transfers data starting from index 0 in the buffer. To specify a different offset, use controlTransfer(int, int, int, int, byte[], int, int, int). //Parameters //requestType //request type for this transaction //request //request ID for this transaction //value //value field for this transaction //index //index field for this transaction //buffer //buffer for data portion of transaction, or null if no data needs to be sent or received //length //the length of the data to send or receive //timeout //in milliseconds //Returns //length of data transferred (or zero) for success, or negative value for failure private void Upload(byte[] data, int length, int blockNum) //throws Exception { //int len = usb.controlTransfer(DFU_RequestType | USB_DIR_IN, DFU_UPLOAD, blockNum, 0, data, length, 100); LibUsbDotNet.Main.UsbSetupPacket setup = new LibUsbDotNet.Main.UsbSetupPacket() { RequestType = (byte)(DFU_RequestType | USB_DIR_IN), Request = (byte)DFU_UPLOAD, Value = (short)blockNum, Index = 0 }; int len = usb.ControlTransfer(setup, data, 0, length); if (len < 0) { throw new Exception("USB comm failed during upload"); } }
// use for firmware download private void Download(byte[] data, int nBlock) //throws Exception { //int len = usb.controlTransfer(DFU_RequestType, DFU_DNLOAD, nBlock, 0, data, data.Length, 0); UsbSetupPacket setup = new LibUsbDotNet.Main.UsbSetupPacket() { RequestType = (byte)(DFU_RequestType), Request = (byte)DFU_DNLOAD, Value = (short)nBlock, Index = 0 }; int len = usb.ControlTransfer(setup, data, 0, data.Length); if (len < 0) { throw new Exception("USB failed during firmware download"); } }
// use for commands private void Download(byte[] data) //throws Exception { //int len = usb.controlTransfer(DFU_RequestType, DFU_DNLOAD, 0, 0, data, data.Length, 50); LibUsbDotNet.Main.UsbSetupPacket setup = new LibUsbDotNet.Main.UsbSetupPacket() { RequestType = (byte)(DFU_RequestType), Request = (byte)DFU_DNLOAD, Value = 0, Index = 0 }; int len = usb.ControlTransfer(setup, data, 0, data.Length); if (len < 0) { throw new Exception("USB Failed during command download"); } }
static void Main(string[] args) { Console.WriteLine("All devices:"); UsbDevice.AllDevices.ToList().ForEach(usbRegistry => { /*foreach (var p in usbRegistry.GetType().GetProperties().Where(p => !p.GetIndexParameters().Any())) * Console.WriteLine(p.Name + " = " + p.GetValue(usbRegistry)); * * Console.WriteLine("props:"); * foreach (var x in usbRegistry.DeviceProperties) * Console.WriteLine(" " + x.Key + " = " + x.Value);*/ UsbDevice device; if (!usbRegistry.Open(out device)) { Console.WriteLine("Unable to open device!"); return; } bool success; LibUsbDotNet.Main.UsbSetupPacket packet = new LibUsbDotNet.Main.UsbSetupPacket(66, 209, 0, 0, 0); int lengthTransferred; success = device.ControlTransfer(ref packet, null, 0, out lengthTransferred); Console.WriteLine("ctl transfer: " + success); Thread.Sleep(2000); Console.WriteLine("Trying to write sth ..."); UsbEndpointWriter writer = device.OpenEndpointWriter(WriteEndpointID.Ep01, EndpointType.Bulk); transferSomething(writer, 0); success = device.Close(); Console.WriteLine("close: " + success); }); Console.WriteLine("Done!"); Console.ReadKey(true); }
public static Boolean checkProtocol(UsbDevice device) { Boolean r = false; string message = ""; short messageLength = 2; UsbSetupPacket setupPacket = new UsbSetupPacket(); setupPacket.RequestType = (byte)((byte)UsbConstants.USB_DIR_IN | (byte) UsbConstants.USB_TYPE_VENDOR); setupPacket.Request = (byte)ACCESSORY_GET_PROTOCOL; setupPacket.Value = 0; setupPacket.Index = 0; setupPacket.Length = 0; int resultTransferred; r = device.ControlTransfer(ref setupPacket, message, messageLength, out resultTransferred); return r; }
private static void SetFnKeyMode(FnKeyMode mode) { UsbDevice keyboard = null; try { keyboard = UsbDevice.OpenUsbDevice(new UsbDeviceFinder(0x046d, 0xc31f)); if (keyboard == null) { throw new KeyboardNotFoundException("Could not find Logitech K290 device. It's not connected or libusb-win32 is not installed."); } var setupPacket = new UsbSetupPacket(0x40, 2, 0x001a, (short)mode, 0); int sentBytesCount; if (keyboard.ControlTransfer(ref setupPacket, null, 0, out sentBytesCount) == false) { throw new ApplicationException( string.Format( "Error transferring control data to the device. Code: {0}. Message: {1}.", UsbDevice.LastErrorNumber, UsbDevice.LastErrorString)); } } catch { throw; } finally { if (keyboard != null) { keyboard.Close(); } UsbDevice.Exit(); } }
// TODO: this is limited to stm32f405RG and will fail for other future chips. private int DeviceSizeLimit() { // retrieves and compares the Internal Flash Memory Size and compares to constant string int bmRequest = 0x80; // IN, standard request to usb device byte bRequest = (byte)0x06; // USB_REQ_GET_DESCRIPTOR byte wLength = (byte)127; // max string size byte[] descriptor = new byte[wLength]; /* This method can be used to retrieve any memory location size by incrementing the wValue in the defined range. * ie. Size of: Internal Flash, Option Bytes, OTP Size, and Feature location */ int wValue = 0x0304; // possible strings range from 0x304-0x307 //int len = usb.controlTransfer(bmRequest, bRequest, wValue, 0, descriptor, wLength, 500); UsbSetupPacket setup = new LibUsbDotNet.Main.UsbSetupPacket() { RequestType = (byte)(bmRequest), Request = (byte)bRequest, Value = (short)wValue, Index = 0 }; var len = usb.ControlTransfer(setup, descriptor, 0, wLength); if (len < 0) { return(-1); } string decoded = Encoding.Unicode.GetString(descriptor); //new string(descriptor, Charset.forName("UTF-16LE")); if (decoded.Contains(mInternalFlashString)) { return(mInternalFlashSize); // size of stm32f405RG } else { return(-1); } }
private void GetStatus(DfuStatus status) //throws Exception { byte[] buffer = new byte[6]; //int length = usb.controlTransfer(DFU_RequestType | USB_DIR_IN, DFU_GETSTATUS, 0, 0, buffer, 6, 500); LibUsbDotNet.Main.UsbSetupPacket setup = new LibUsbDotNet.Main.UsbSetupPacket() { RequestType = (byte)(DFU_RequestType | USB_DIR_IN), Request = (byte)DFU_GETSTATUS, Value = 0, Index = 0 }; int length = usb.ControlTransfer(setup, buffer, 0, 6); if (length < 0) { throw new Exception("USB Failed during getStatus"); } status.bStatus = buffer[0]; // state during request status.bState = buffer[4]; // state after request status.bwPollTimeout = (buffer[3] & 0xFF) << 16; status.bwPollTimeout |= (buffer[2] & 0xFF) << 8; status.bwPollTimeout |= (buffer[1] & 0xFF); }
public void OnControlRequestReceived(ControlRequestEventArgs e) { if ((e.bmRequestType == 0x80) && (e.bRequest == 0x06)) { //Descriptor request, let the other event handle it } else if ((e.bmRequestType == 0x00) && (e.bRequest == 0x05)) { //Let the library handle it, needs it to set the address in the Teensy } else if ((e.bmRequestType == 0x00) && (e.bRequest == 0x09)) { //Let the library handle it, needs it to configure the endpoints in the Teensy } else { //Issue the request to the real device, and return whatever it did var setup = new UsbSetupPacket((byte)e.bmRequestType, (byte)e.bRequest, (short)e.wValue, (short)e.wIndex, (short)e.wLength); int transferred; if ((e.bmRequestType & 0x80) > 0) { var ret = new byte[e.wLength]; _forwardee.ControlTransfer(ref setup, ret, ret.Length, out transferred); e.ReturnData = new byte[transferred]; Array.Copy(ret, 0, e.ReturnData, 0, e.ReturnData.Length); } else { _forwardee.ControlTransfer(ref setup, e.AttachedData, e.AttachedData.Length, out transferred); } e.Ignore = false; } }
private void timer1_Tick(object sender, EventArgs e) { //double t = (ti++)/1000.0; //plotter.AddData(2); if (_usbDevice != null) { s.Restart(); UsbSetupPacket setup = new UsbSetupPacket((byte)(UsbCtrlFlags.RequestType_Vendor | UsbCtrlFlags.Recipient_Device | UsbCtrlFlags.Direction_In), (byte)OUSBRequest.ReadADCBuffer, 0, 0, 0); int length; if (!_usbDevice.ControlTransfer(ref setup, buffer, buffer.Length, out length)) usbDisconnected(); else if (length >= 2) { double time = (double)BitConverter.ToInt16(buffer, 0) / 250000.0; if (plotter.SampleTime == 0) plotter.SampleTime = time; else plotter.SampleTime = (plotter.SampleTime*19 + time)/20; //int time = BitConverter.ToInt16(buffer, 0); //lblOut.Text = time.ToString(); //plotter.AddData(time); for (int i = 2; i<length; i += 2) { double adc = BitConverter.ToInt16(buffer, i) * 5.0 / 1024.0; plotter.AddData(adc); } } s.Stop(); double elapsed = s.ElapsedTicks * 1000.0 / Stopwatch.Frequency; lblOut.Text = plotter.SampleTime.ToString(); } }
/// <summary> /// Gets the selected alternate interface of the specified interface. /// </summary> /// <param name="interfaceID">The interface settings number (index) to retrieve the selected alternate interface setting for.</param> /// <param name="selectedAltInterfaceID">The alternate interface setting selected for use with the specified interface.</param> /// <returns>True on success.</returns> public bool GetAltInterfaceSetting(byte interfaceID, out byte selectedAltInterfaceID) { byte[] buf = new byte[1]; int uTransferLength; UsbSetupPacket setupPkt = new UsbSetupPacket(); setupPkt.RequestType = (byte) UsbEndpointDirection.EndpointIn | (byte) UsbRequestType.TypeStandard | (byte) UsbRequestRecipient.RecipInterface; setupPkt.Request = (byte) UsbStandardRequest.GetInterface; setupPkt.Value = 0; setupPkt.Index = interfaceID; setupPkt.Length = 1; bool bSuccess = ControlTransfer(ref setupPkt, buf, buf.Length, out uTransferLength); if (bSuccess && uTransferLength == 1) selectedAltInterfaceID = buf[0]; else selectedAltInterfaceID = 0; return bSuccess; }
/// <summary> /// Transmits control data over a default control endpoint. /// </summary> /// <param name="setupPacket">An 8-byte setup packet which contains parameters for the control request. /// See section 9.3 USB Device Requests of the Universal Serial Bus Specification Revision 2.0 for more information. </param> /// <param name="buffer">Data to be sent/received from the device.</param> /// <param name="bufferLength">Length of the buffer param.</param> /// <param name="lengthTransferred">Number of bytes sent or received (depends on the direction of the control transfer).</param> /// <returns>True on success.</returns> public virtual bool ControlTransfer(ref UsbSetupPacket setupPacket, object buffer, int bufferLength, out int lengthTransferred) { PinnedHandle pinned = new PinnedHandle(buffer); bool bSuccess = ControlTransfer(ref setupPacket, pinned.Handle, bufferLength, out lengthTransferred); pinned.Dispose(); return bSuccess; }
/// <summary> /// Transmits control data over a default control endpoint. /// </summary> /// <param name="setupPacket">An 8-byte setup packet which contains parameters for the control request. /// See section 9.3 USB Device Requests of the Universal Serial Bus Specification Revision 2.0 for more information. </param> /// <param name="buffer">Data to be sent/received from the device.</param> /// <param name="bufferLength">Length of the buffer param.</param> /// <param name="lengthTransferred">Number of bytes sent or received (depends on the direction of the control transfer).</param> /// <returns>True on success.</returns> public virtual bool ControlTransfer(ref UsbSetupPacket setupPacket, IntPtr buffer, int bufferLength, out int lengthTransferred) { bool bSuccess = mUsbApi.ControlTransfer(mUsbHandle, setupPacket, buffer, bufferLength, out lengthTransferred); if (!bSuccess) UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "ControlTransfer", this); return bSuccess; }
private static Byte[] GetReport() { int expected = 8; Byte[] data = new Byte[expected]; UsbSetupPacket packet = new UsbSetupPacket((byte)UsbRequestType.TypeVendor | (byte)UsbRequestRecipient.RecipDevice | (byte)UsbEndpointDirection.EndpointIn, (byte)Request.GetReport, 0, 0, 0); int transfered; device.ControlTransfer(ref packet, data, data.Length, out transfered); return data; }
public static void WriteFlashBlock(UInt16 address, Byte[] data) { UsbSetupPacket packet = new UsbSetupPacket((byte)UsbRequestType.TypeVendor | (byte)UsbRequestRecipient.RecipDevice | (byte)UsbEndpointDirection.EndpointOut, (byte)Request.WriteFlashBlock, (short)address, 0, (short)data.Length); int transfered; device.ControlTransfer(ref packet, data, data.Length, out transfered); if (transfered != data.Length) throw new CommunicationException("Error sending data to device"); }
public static void Reboot() { UsbSetupPacket packet = new UsbSetupPacket((byte)UsbRequestType.TypeVendor | (byte)UsbRequestRecipient.RecipDevice | (byte)UsbEndpointDirection.EndpointOut, (byte)Request.Reboot, 0, 0, 0); int transfered; object buffer = null; device.ControlTransfer(ref packet, buffer, 0, out transfered); Disconnect(); }
/// <summary> /// Sends command to uDMX /// </summary> /// <returns><c>true</c>, if command was sent, <c>false</c> otherwise.</returns> /// <param name="command">Command.</param> /// <param name="cvalue">Cvalue.</param> /// <param name="cindex">Cindex.</param> /// <param name="buffer">Buffer.</param> private bool SendCommand(Command command, short cvalue, short cindex, byte[] buffer) { bool result = false; int transfered; UsbSetupPacket packet = new UsbSetupPacket (); // This is alegedly ignored by the uDMX, but let's play nice packet.RequestType = (byte)UsbRequestType.TypeVendor | (byte)UsbRequestRecipient.RecipDevice | (byte)UsbEndpointDirection.EndpointOut; packet.Request = (byte)command; packet.Value = cvalue; packet.Index = cindex; packet.Length = cvalue; // create empty buffer if the buffer is null if (buffer == null) buffer = new byte[0]; // Send data and get the result if (_device.ControlTransfer (ref packet, buffer, buffer.Length, out transfered)) { result = true; } return result; }
/// <summary> /// Set a GPIO pin output /// </summary> /// <param name="pin">Pin number</param> private void setPinOutput(byte pin) { byte[] buffer_ = new byte[8]; int whatIsThis = 8; MySetupPacket = new UsbSetupPacket(0xC0, 14, pin, 0, 8); lwStatus = MyUsbDevice.ControlTransfer(ref MySetupPacket, buffer_, 8, out whatIsThis); }
/// <summary> /// Sets the state of the internal pullup resistor. /// </summary> /// <param name="pin">Pin number</param> /// <param name="state">ENABLE or DISABLE</param> private void internalPullup(byte pin, byte state) { byte[] buffer_ = new byte[8]; int whatIsThis = 8; if(state==ENABLE) MySetupPacket = new UsbSetupPacket(0xC0, 18, pin, 0, 8); else MySetupPacket = new UsbSetupPacket(0xC0, 19, pin, 0, 8); lwStatus = MyUsbDevice.ControlTransfer(ref MySetupPacket, buffer_, 8, out whatIsThis); }
/// <summary> /// Change the SPI message frequency by adjusting delay duration. By default, Little-Wire sends the SPI messages with maximum speed. /// If your hardware can't catch up with the speed, increase the duration value to lower the SPI speed. /// </summary> /// <param name="duration">Amount of delay</param> public void spi_updateDelay(byte duration) { byte[] buffer_ = new byte[8]; int whatIsThis = 8; MySetupPacket = new UsbSetupPacket(0xC0, 31, duration, 0, 8); lwStatus = MyUsbDevice.ControlTransfer(ref MySetupPacket, buffer_, 8, out whatIsThis); }
/// <summary> /// Send SPI message(s). SPI Mode is 0. /// </summary> /// <param name="sendBuffer">Message array to send</param> /// <param name="inputBuffer">Returned array message</param> /// <param name="length">Mesage length -> Max = 4</param> /// <param name="mode">AUTO_CS or MANUAL_CS</param> public void spi_sendMessage(byte[] sendBuffer, byte[] inputBuffer, byte length, byte mode) { byte[] buffer_ = new byte[8]; int whatIsThis = 8; MySetupPacket = new UsbSetupPacket(0xC0, (byte)(0xF0 + length + (byte)(mode << 3)), (short)((sendBuffer[1] << 8) + sendBuffer[0]), (short)((sendBuffer[3] << 8) + sendBuffer[2]), 8); lwStatus = MyUsbDevice.ControlTransfer(ref MySetupPacket, buffer_, 8, out whatIsThis); MySetupPacket = new UsbSetupPacket(0xC0, 40, 0, 0, 8); lwStatus = MyUsbDevice.ControlTransfer(ref MySetupPacket, buffer_, 8, out whatIsThis); for(int i=0;i<length;i++) inputBuffer[i]=buffer_[i]; }
/// <summary> /// Gets the USB devices active configuration value. /// </summary> /// <param name="config">The active configuration value. A zero value means the device is not configured and a non-zero value indicates the device is configured.</param> /// <returns>True on success.</returns> public virtual bool GetConfiguration(out byte config) { config = 0; byte[] buf = new byte[1]; int uTransferLength; UsbSetupPacket setupPkt = new UsbSetupPacket(); setupPkt.RequestType = (byte) UsbEndpointDirection.EndpointIn | (byte) UsbRequestType.TypeStandard | (byte) UsbRequestRecipient.RecipDevice; setupPkt.Request = (byte) UsbStandardRequest.GetConfiguration; setupPkt.Value = 0; setupPkt.Index = 0; setupPkt.Length = 1; bool bSuccess = ControlTransfer(ref setupPkt, buf, buf.Length, out uTransferLength); if (bSuccess && uTransferLength == 1) { config = buf[0]; mCurrentConfigValue = config; return true; } UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "GetConfiguration", this); return false; }
public static Byte[] ReadEepromBlock(UInt16 address, int length) { Byte[] data = new Byte[length]; UsbSetupPacket packet = new UsbSetupPacket((byte)UsbRequestType.TypeVendor | (byte)UsbRequestRecipient.RecipDevice | (byte)UsbEndpointDirection.EndpointIn, (byte)Request.ReadEepromBlock, (short)address, 0, (short)data.Length); int transfered; device.ControlTransfer(ref packet, data, data.Length, out transfered); return data; }
public int sendCommand(byte command, short value, short index) { byte[] buffer = new byte[4]; int actuallySent = 0; int counter = 0; // abuse the setup packet to send five bytes UsbSetupPacket usp = new UsbSetupPacket((byte)((byte)UsbRequestType.TypeVendor | (byte)UsbRequestRecipient.RecipDevice | (byte)UsbEndpointDirection.EndpointIn), command, value, index, (short)buffer.Length); while(actuallySent != buffer.Length) // could check buffer for the return values (since the firmware returns the same values back) but it might be faster to omit the return values on the trinket side { MyUsbDevice.ControlTransfer(ref usp, buffer, buffer.Length, out actuallySent); counter++; if (counter >= 100) { throw new Exception(string.Format("ControlTransfer failed after {0} tries", counter)); } //if (MyUsbDevice.ControlTransfer(ref usp, buffer, buffer.Length, out actuallySent)) // return "Trinket says: " + buffer[0] + " " + buffer[1] + " " + buffer[2] + " " + buffer[3] +" Actually sent: "+actuallySent.ToString() + " "; //else // return Environment.NewLine + "Command" + command.ToString() + "failed." + " Actually sent: " + actuallySent.ToString() + Environment.NewLine; } //return "Trinket says: " + buffer[0] + " " + buffer[1] + " " + buffer[2] + " " + buffer[3] + " Actually sent: " + actuallySent.ToString() + " Tries: " + counter.ToString(); return counter; }
/** * Finds all controllers, connects them to their own sockets, and sends input over those sockets. */ public static void Main(string[] args) { ErrorCode ec = ErrorCode.None; controllers = getControllers(); try { for (int i = 0; i < controllers.Length; i++) { if (controllers[i] == null) break; UsbDevice controller = controllers[i]; // already opened IUsbDevice device = controller as IUsbDevice; device.SetConfiguration(1); device.ClaimInterface(0); // setup this controller's socket IPAddress ip = Dns.GetHostEntry("localhost").AddressList[1]; // won't always be list[1] IPEndPoint ipe = new IPEndPoint(ip, ports[i]); Socket s = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp); s.Connect(ipe); sockets[i] = s; Console.WriteLine("Socket " + i + " connected?: " + s.Connected); } while (true) { for (int i = 0; i < controllers.Length; i++) { if (controllers[i] == null) break; byte[] status_packet = new byte[49]; int len = 0; UsbSetupPacket setup = new UsbSetupPacket(0xa1, 0x01, 0x0101, 0, 0x31); // magic values controllers[i].ControlTransfer(ref setup, status_packet, 49, out len); // send to UI byte[] rearranged = rearrangeStatus(status_packet); sockets[i].Send(rearranged, 12, 0); } Thread.Sleep(50); } } catch (Exception ex) { Console.WriteLine(); Console.WriteLine((ec != ErrorCode.None ? ec + ":" : String.Empty) + ex.Message); } finally // cleanup { for(int i = 0; i < controllers.Length; i++){ if (controllers[i] != null) { UsbDevice controller = controllers[i]; if (controller != null && controller.IsOpen) { IUsbDevice device = controller as IUsbDevice; device.ReleaseInterface(0); controller.Close(); } } } UsbDevice.Exit(); Console.ReadKey(); } }
/// <summary> /// Transmits control data over a default control endpoint. /// </summary> /// <param name="setupPacket">An 8-byte setup packet which contains parameters for the control request. /// See section 9.3 USB Device Requests of the Universal Serial Bus Specification Revision 2.0 for more information. </param> /// <param name="buffer">Data to be sent/received from the device.</param> /// <param name="bufferLength">Length of the buffer param.</param> /// <param name="lengthTransferred">Number of bytes sent or received (depends on the direction of the control transfer).</param> /// <returns>True on success.</returns> public override bool ControlTransfer(ref UsbSetupPacket setupPacket, IntPtr buffer, int bufferLength, out int lengthTransferred) { Debug.WriteLine(GetType().Name + ".ControlTransfer() Before", "Libusb-1.0"); int ret = LibUsbApi.ControlTransferAsync((LibUsbDeviceHandle) mUsbHandle, setupPacket.RequestType, setupPacket.Request, setupPacket.Value, setupPacket.Index, buffer, (short) bufferLength, UsbConstants.DEFAULT_TIMEOUT); Debug.WriteLine(GetType().Name + ".ControlTransfer() Error:" + ((global::LibUsb.LibUsbError) ret).ToString(), "Libusb-1.0"); if (ret < 0) { UsbError.Error(ErrorCode.MonoApiError, ret, "ControlTransfer Failed", this); lengthTransferred = 0; return false; } lengthTransferred = ret; return true; }
/// <summary> /// Updates the values of softPWM modules /// </summary> /// <param name="ch1">Value of channel 1 - pin4</param> /// <param name="ch2">Value of channel 2 - pin1</param> /// <param name="ch3">Value of channel 3 - pin2</param> public void softPWM_write(byte ch1, byte ch2, byte ch3) { byte[] buffer_ = new byte[8]; int whatIsThis = 8; MySetupPacket = new UsbSetupPacket(0xC0, 48, (short)((ch2 << 8) | ch1), ch3, 8); lwStatus = MyUsbDevice.ControlTransfer(ref MySetupPacket, buffer_, 8, out whatIsThis); }
/// <summary> /// Sends the control request to set the test mode /// </summary> private static int Bench_SetTestType(UsbDevice dev, BENCHMARK_DEVICE_TEST_TYPE testType, int intf) { int transferred; byte[] dataBuffer = new byte[1]; UsbSetupPacket setTestTypePacket = new UsbSetupPacket((byte) (UsbCtrlFlags.Direction_In | UsbCtrlFlags.Recipient_Device | UsbCtrlFlags.RequestType_Vendor), (byte)BENCHMARK_DEVICE_COMMANDS.SET_TEST, (short) testType, (short) intf, 1); bool success = dev.ControlTransfer(ref setTestTypePacket, dataBuffer, dataBuffer.Length, out transferred); if (!success) return -1; return transferred; }
/// <summary> /// Initialize the SPI module /// </summary> public void spi_init() { byte[] buffer_ = new byte[8]; int whatIsThis = 8; MySetupPacket = new UsbSetupPacket(0xC0, 23, 0, 0, 8); lwStatus = MyUsbDevice.ControlTransfer(ref MySetupPacket, buffer_, 8, out whatIsThis); }