public async Task<bool> SendControl(int cmd1, int cmd2, int cmd3) { var bytes = new[] { Convert.ToByte(cmd1), Convert.ToByte(cmd2), Convert.ToByte(cmd3) }; var buffer = bytes.AsBuffer(); var setupPacket = new UsbSetupPacket(); var requestType = new UsbControlRequestType(); requestType.ControlTransferType = UsbControlTransferType.Vendor; requestType.Direction = UsbTransferDirection.Out; requestType.Recipient = UsbControlRecipient.Device; setupPacket.RequestType = requestType; setupPacket.Request = 6; setupPacket.Value = 0x0100; setupPacket.Length = buffer.Length; setupPacket.Index = 0; var transferred = await _usbDevice.SendControlOutTransferAsync(setupPacket, buffer); return (transferred == buffer.Length); }
private void Normal() { UsbSetupPacket packet = new UsbSetupPacket(); UsbSetupPacket packetread = new UsbSetupPacket(); byte[] readBuffer = new byte[8]; byte buf = 0x14; int transfer = 0x08; packet.Value = 0x00; packet.Index = 0x00; packet.Length = 0x8; packet.Request = 0x30; packet.RequestType = (byte)UsbRequestType.TypeVendor; packetread.Value = 0x00; packetread.Index = 0x00; packetread.Length = 0x8; packetread.Request = 0x31; packetread.RequestType = 0xC0; Console.WriteLine("Setting ISD2100 to normal mode.."); MyUsbDevice.ControlTransfer(ref packet, buf, 1, out transfer); if (MainForm.debugme) { Console.WriteLine("Length Transferred: {0}", transfer); } MyUsbDevice.ControlTransfer(ref packetread, readBuffer, 8, out transfer); if (MainForm.debugme) { Console.WriteLine("Length Transferred: {0}", transfer); } Console.WriteLine("Status: 0x{0:X}", readBuffer[0]); }
private static string GetStringDescriptor(byte deviceAddress, byte stringIndex) { try { if (stringIndex == 0) { return("(No data)"); } var getStrSetup = new UsbSetupPacket(UsbStandardRequest.GET_DESCRIPTOR, 0x80) { wValueH = UsbDescriptorType.STRING, wValueL = stringIndex, wLength = 255 }; var zeroStringDesc = usb.ExecuteControlInTransfer(getStrSetup, deviceAddress); if (zeroStringDesc.Length < 4) { return("(Invalid descriptor received)"); } getStrSetup.wIndexL = zeroStringDesc[2]; getStrSetup.wIndexH = zeroStringDesc[3]; var stringDesc = usb.ExecuteControlInTransfer(getStrSetup, deviceAddress); return(Encoding.Unicode.GetString(stringDesc.Skip(2).ToArray())); } catch (Exception ex) { return(ex.Message); } }
protected override void ControlTransfer(Request request, ushort value, ref byte[] indata) { var rtype = new RequestType(UsbEndpointDirection.EndpointIn, UsbRequestType.TypeClass, UsbRequestRecipient.RecipInterface); var s = new UsbSetupPacket(rtype, (byte)request, value, InterfaceID, indata.Length); ControlTransfer(s, indata, indata.Length); }
/// <summary> /// Sets 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> /// <remarks> /// A USB device can have several different configurations, but only one active configuration. /// </remarks> public bool SetConfiguration(byte config) { int uTransferLength; UsbSetupPacket setupPkt = new UsbSetupPacket(); setupPkt.RequestType = (byte)UsbEndpointDirection.EndpointOut | (byte)UsbRequestType.TypeStandard | (byte)UsbRequestRecipient.RecipDevice; setupPkt.Request = (byte)UsbStandardRequest.SetConfiguration; setupPkt.Value = config; setupPkt.Index = 0; setupPkt.Length = 0; bool bSuccess = ControlTransfer(ref setupPkt, null, 0, out uTransferLength); if (bSuccess) { mCurrentConfigValue = config; } else { UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "SetConfiguration", this); } return(bSuccess); }
/// <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 string SendCommand(Command command, short cvalue, short cindex, byte[] buffer) { 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 (!IsOpen) { return("o dispositivo " + PRODUCT + " não está ligado"); } int transfered; if (_device.ControlTransfer(ref packet, buffer, buffer.Length, out transfered)) { return(""); } return("erro ao enviar comando " + command + "para o dispositivo " + PRODUCT); }
public static bool GetTestType(UsbDevice usbTestDevice, out UsbTestType usbTestType, byte interfaceID) { if (ReferenceEquals(usbTestDevice, null)) { throw new UsbTestDeviceException("UsbTestDevice must be set before invoking this member!"); } int lengthTransferred; byte[] buf = new byte[1]; UsbSetupPacket cmd = UsbCmdGetTestType; cmd.Index = interfaceID; bool bSuccess = usbTestDevice.ControlTransfer(ref cmd, buf, buf.Length, out lengthTransferred); if (bSuccess && lengthTransferred == 1) { usbTestType = (UsbTestType)buf[0]; return(true); } usbTestType = UsbTestType.Invalid; return(false); }
public static bool SetTestType(UsbDevice usbTestDevice, UsbTestType usbTestType, bool bCheck, byte interfaceID) { if (ReferenceEquals(usbTestDevice, null)) { throw new UsbTestDeviceException("UsbTestDevice must be set before invoking this member!"); } if (bCheck) { UsbTestType bCurrentTestType; if (GetTestType(usbTestDevice, out bCurrentTestType, interfaceID)) { if (bCurrentTestType == usbTestType) { return(true); } } else { return(false); } } int lengthTransferred; byte[] buf = new byte[1]; UsbSetupPacket cmd = UsbCmdSetTestType; cmd.Value = (short)usbTestType; cmd.Index = interfaceID; bool bSuccess = usbTestDevice.ControlTransfer(ref cmd, buf, buf.Length, out lengthTransferred); return(bSuccess && lengthTransferred == 1); }
public static bool ReadEEDATA(UsbDevice usbTestDevice, byte address, out byte value) { if (ReferenceEquals(usbTestDevice, null)) { throw new UsbTestDeviceException("UsbTestDevice must be set before invoking this member!"); } int lengthTransferred; byte[] buf = new byte[1]; UsbSetupPacket cmd = UsbCmdReadEEDATA; cmd.Value = address; bool bSuccess = usbTestDevice.ControlTransfer(ref cmd, buf, buf.Length, out lengthTransferred); if (bSuccess && lengthTransferred == 1) { value = buf[0]; return(true); } value = 0; return(false); }
/// <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)EndpointDirection.In | (byte)UsbRequestType.TypeStandard | (byte)UsbRequestRecipient.RecipInterface; setupPkt.Request = (byte)StandardRequest.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> /// 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); }
private void Start() { byte requestType = (0x01 << 5) | 0x80; const byte request = 0x01; short val = 0x03 << 8; byte[] readBuffer = new byte[512]; var packet = new UsbSetupPacket(requestType, request, val, 0, 1); while (true) { if (_myUsbDevice == null) { return; } _myUsbDevice.ControlTransfer(ref packet, readBuffer, 512, out var transferred); if (transferred != 0) { this.Invoke((MethodInvoker) delegate { OnReceiveEndPointData(readBuffer, transferred); }); } } }
public static bool sendControlMessage(UsbDevice device, byte requestCode, short index, string message) { short messageLength = 0; if (message != null) { messageLength = (short)message.Length; } UsbSetupPacket setupPacket = new UsbSetupPacket(); setupPacket.RequestType = (byte)((byte)UsbConstants.USB_DIR_OUT | (byte)UsbConstants.USB_TYPE_VENDOR); setupPacket.Request = requestCode; setupPacket.Value = 0; setupPacket.Index = index; setupPacket.Length = messageLength; Console.WriteLine("RequestType:" + setupPacket.RequestType); Console.WriteLine("setupPacket.Request:" + setupPacket.Request); Console.WriteLine("setupPacket.Value:" + setupPacket.Value); Console.WriteLine("setupPacket.Index:" + setupPacket.Index); Console.WriteLine("setupPacket.Length:" + setupPacket.Length); Console.WriteLine("message:" + message); byte[] messageBytes = null; if (null != message) { messageBytes = Encoding.UTF8.GetBytes(message); } return(device.ControlTransfer(ref setupPacket, messageBytes, messageLength, out int resultTransferred)); }
private void CloseDevice(UsbDevice device) { if (device == null) { throw new ArgumentNullException("device"); } if (!device.IsOpen) { Trace.WriteLine("Device already closed, skipping."); return; } var control = new UsbSetupPacket(0x40, 0x02, 0x0004, 0, 0); int transferLength = 0; device.ControlTransfer(ref control, m_readBuffer, m_readBuffer.Length, out transferLength); if (device.Close()) { Trace.WriteLine("Device closed"); } else { Trace.WriteLine("Device could not be closed."); } }
protected override void ControlTransfer(Request request, ushort value = 0) { var rtype = new RequestType(UsbEndpointDirection.EndpointOut, UsbRequestType.TypeClass, UsbRequestRecipient.RecipInterface); var s = new UsbSetupPacket(rtype, (byte)request, value, InterfaceID, 0); ControlTransfer(s, null, 0); }
/// <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); }
/// <summary> /// /// </summary> /// <param name="device"></param> /// <remarks> /// Éste método NO REVISA si los comandos de control se enviaron correctamente, /// pues al parecer LibUsbDotNet o Silicon Labs no determinan correctamente si /// el comando se recibió correctamente; sin embargo, los comandos de control /// se envían y la única forma de determinar éxito o fracaso es capturando una /// excepción con el Código de Error IoTimeout. /// </remarks> private void OpenDevice(UsbDevice device) { if (device == null) { throw new ArgumentNullException("device"); } if (m_deviceInitialized) { Trace.WriteLine("Device already intialized, skipping."); return; } int transferLength = 0; var control = new UsbSetupPacket(0x40, 0x00, Int16.MaxValue, 0, 0); device.ControlTransfer(ref control, m_readBuffer, m_readBuffer.Length, out transferLength); var bulkWrite = device.OpenEndpointWriter(WriteEndpointID.Ep01); if (bulkWrite.Reset()) { Trace.WriteLine("--- > [OK] Bulk Write Initial Reset"); } else { Trace.WriteLine("--- > [Error] Bulk Write Initial Reset"); Trace.WriteLine(" [Error] " + UsbDevice.LastErrorString); } var bulkRead = device.OpenEndpointReader(ReadEndpointID.Ep01, 256); if (bulkRead.Reset()) { Trace.WriteLine("--- > [OK] Bulk Read Initial Reset"); } else { Trace.WriteLine("--- > [Error] Bulk Read Initial Reset"); Trace.WriteLine(" [Error] " + UsbDevice.LastErrorString); } control = new UsbSetupPacket(0x40, 0x02, 0x0002, 0, 0); device.ControlTransfer(ref control, m_readBuffer, m_readBuffer.Length, out transferLength); // Necesario para iniciar la comunicación con el dispostivo try { DeviceDateTimeUtcOffset = Request <DateTime>(device, Interop.Blockity.RequestCommands.GetDateTime()) - DateTime.UtcNow; } catch (KmsUsbDeviceException ex) { throw new KmsUsbDeviceException( this, ex.UsbErrorCode, "Device protocol communication could not be initialized.", ex ); } m_deviceInitialized = true; }
private void tx(byte bRequest, short wValue) { byte[] buffer = new byte[256]; int transferred = 0; UsbSetupPacket setup = new UsbSetupPacket((byte)UsbRequestType.TypeVendor, bRequest, wValue, 0x00, 0x00); bool result = this.device.ControlTransfer(ref setup, buffer, 0x0000, out transferred); }
private void Form1_FormClosed(object sender, FormClosedEventArgs e) { UsbSetupPacket packet = new UsbSetupPacket((byte)(UsbCtrlFlags.RequestType_Vendor | UsbCtrlFlags.Recipient_Device | UsbCtrlFlags.Direction_Out), 1, (short)0, 0, 0); int countIn; byte[] data = new byte[1]; MyUsbDevice.ControlTransfer(ref packet, data, 0, out countIn); }
/// <summary> /// Set a GPIO pin output /// </summary> /// <param name="pin">Pin number</param> public void setPinOutput(byte pin) { byte[] buffer_ = new byte[8]; int whatIsThis = 8; MySetupPacket = new UsbSetupPacket(0xC0, 14, pin, 0, 8); MyUsbDevice.ControlTransfer(ref MySetupPacket, buffer_, 8, out whatIsThis); }
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> /// Initialize the Pwm module on the device /// </summary> public void initPwm() { byte[] buffer_ = new byte[8]; int whatIsThis = 8; MySetupPacket = new UsbSetupPacket(0xC0, 16, 0, 0, 8); MyUsbDevice.ControlTransfer(ref MySetupPacket, buffer_, 8, out whatIsThis); }
/// <summary> /// Update the compare values of Pwm outputs /// </summary> /// <param name="channelA">Channel A</param> /// <param name="channelB">Channel B</param> public void updatePwmCompare(byte channelA, byte channelB) { byte[] buffer_ = new byte[8]; int whatIsThis = 8; MySetupPacket = new UsbSetupPacket(0xC0, 17, channelA, channelB, 8); MyUsbDevice.ControlTransfer(ref MySetupPacket, buffer_, 8, out whatIsThis); }
public bool transfer_out(byte request, int value, ref byte[] data, int length, out int actual) { bool rval; UsbSetupPacket setup = new UsbSetupPacket(0x21, request, value, DFUinterface, length); rval=myUSBDevice.ControlTransfer(ref setup, data, length, out actual); return(rval); }
public void Reset() { UsbSetupPacket sup = new UsbSetupPacket(0x40, 0x02, 0, 0, 0); byte[] buffer = new byte[0]; int len; dev.ControlTransfer(ref sup, buffer, 0, out len); }
/// <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); }
public void TurnLightningOn(byte colorByte) { //Зажигаем UsbSetupPacket packet = new UsbSetupPacket((byte)(UsbCtrlFlags.RequestType_Vendor | UsbCtrlFlags.Recipient_Device | UsbCtrlFlags.Direction_Out), 1, colorByte, 0, 0); int countIn; byte[] data = new byte[1]; _orbDevice.ControlTransfer(ref packet, data, 0, out countIn); }
public void SetConfiguration(RadioConfiguration conf) { byte[] c = new byte[16]; for (int i = 0; i < 5; i++) { if (!conf.Pipes[i].Enabled) { continue; } byte info = 1 << 7; if (conf.Pipes[i].AutoAcknowledge) { info |= 1 << 6; } if (conf.Pipes[i].DynamicPayload) { info |= 0x3F; } else { info |= conf.Pipes[i].PayloadWidth; } c[i * 2] = info; c[(i * 2) + 1] = conf.Pipes[i].Address; } c[10] = conf.Channel; byte misc = 0; misc |= (byte)(((byte)conf.Rate) << 6); misc |= (byte)(((byte)conf.Power) << 4); misc |= (byte)(conf.RetransmitCount & 0xF); c[11] = misc; for (int b = 0; b < 4; b++) { c[12 + b] = conf.AddressPrefix[b]; } UsbSetupPacket sup = new UsbSetupPacket(0x40, 0x01, 0, 0, 16); int l; dev.ControlTransfer(ref sup, c, 16, out l); if (l != 16) { throw new Exception($"{l} bytes written"); } }
/// <summary> /// Send a one byte SPI message. /// </summary> /// <param name="message">Message to send</param> public byte sendSpiMessage(byte message) { byte[] buffer_ = new byte[8]; int whatIsThis = 8; MySetupPacket = new UsbSetupPacket(0xC0, 21, message, 0, 8); MyUsbDevice.ControlTransfer(ref MySetupPacket, buffer_, 8, out whatIsThis); return(buffer_[0]); }
/// <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> /// Read a state of a GPIO pin /// </summary> /// <param name="pin">Pin number</param> /// <returns>1 for HIGH, 0 for LOW</returns> public byte digitalRead(byte pin) { byte[] buffer_ = new byte[8]; int whatIsThis = 8; MySetupPacket = new UsbSetupPacket(0xC0, 20, pin, 0, 8); MyUsbDevice.ControlTransfer(ref MySetupPacket, buffer_, 8, out whatIsThis); return(buffer_[0]); }
/// <summary> /// Sets up a UsbSetupPacket and sends control transfer that will let the device know that we are trying to retrieve data from the device. /// This method only supports vendor commands because the scenario only uses vendor commands. /// /// Do note the method that is used to send a control transfer. There are two methods to send a control transfer. /// One involves receiving buffer data in the Data stage of the control transfer, and the other involves transmiting the buffer data. /// /// The simplest way to obtain a byte from the buffer is by using a DataReader. DataReader provides a simple way /// to read from buffers (e.g. can return bytes, strings, ints). /// </summary> /// <param name="vendorCommand">Command to put into SetupPacket's Request property</param> /// <param name="dataPacketLength">Number of bytes in the data packet that is sent in the Data Stage</param> /// <returns>A task that can be used to chain more methods after completing the scenario</returns> async Task<IBuffer> SendVendorControlTransferInToDeviceRecipientAsync(Byte vendorCommand, UInt32 dataPacketLength) { // Data will be written to this buffer when we receive it var buffer = new Windows.Storage.Streams.Buffer(dataPacketLength); UsbSetupPacket setupPacket = new UsbSetupPacket { RequestType = new UsbControlRequestType { Direction = UsbTransferDirection.In, Recipient = UsbControlRecipient.Device, ControlTransferType = UsbControlTransferType.Vendor, }, Request = vendorCommand, Length = dataPacketLength }; return await EventHandlerForDevice.Current.Device.SendControlInTransferAsync(setupPacket, buffer); }
/// <summary> /// Sets the seven segment display on the OSRFX2 device via control transfer /// /// Before sending the data through the control transfer, the numeric value is converted into a hex value that is /// bit masked. Different sections of the bit mask will turn on a different LEDs. Please refer to the OSRFX2 spec /// to see the hex values per LED. /// /// Any errors in async function will be passed down the task chain and will not be caught here because errors should be /// handled at the end of the task chain. /// /// Setting Seven Segment LED require setup packet: /// bmRequestType: type: VENDOR /// recipient: DEVICE /// bRequest: 0xDB /// wLength: 1 /// /// The Buffer is used to hold data that is meant to be sent over during the data phase. /// The easiest way to write data to an IBuffer is to use a DataWriter. The DataWriter, when instantiated, /// creates a buffer internally. The buffer is of type IBuffer and can be detached from the writer, which gives us /// the internal IBuffer. /// </summary> /// <param name="numericValue"></param> /// <returns>A task that can be used to chain more methods after completing the scenario</returns> async Task SetOsrFx2SevenSegmentAsync(Byte numericValue) { DataWriter writer = new DataWriter(); // Convert the numeric value into a 7 segment LED hex value and write it to a buffer. writer.WriteByte(OsrFx2.SevenLedSegmentMask[numericValue]); // The buffer with the data var bufferToSend = writer.DetachBuffer(); UsbSetupPacket setupPacket = new UsbSetupPacket { RequestType = new UsbControlRequestType { Direction = UsbTransferDirection.Out, Recipient = UsbControlRecipient.Device, ControlTransferType = UsbControlTransferType.Vendor }, Request = OsrFx2.VendorCommand.SetSevenSegment, Value = 0, Length = bufferToSend.Length }; UInt32 bytesTransferred = await EventHandlerForDevice.Current.Device.SendControlOutTransferAsync(setupPacket, bufferToSend); // Make sure we sent the correct number of bytes if (bytesTransferred == bufferToSend.Length) { MainPage.Current.NotifyUser("The segment display value is set to " + numericValue.ToString(), NotifyType.StatusMessage); } else { MainPage.Current.NotifyUser( "Error sending data. Sent bytes: " + bytesTransferred.ToString() + "; Tried to send : " + bufferToSend.Length, NotifyType.ErrorMessage); } }
/// <summary> /// Sends a raw CDC request. /// </summary> /// <param name="index">Interface index.</param> /// <param name="requestType">UsbControlRequestType for CDC request.</param> /// <param name="request">CDC request code.</param> /// <param name="value">value, corresponded with the request code.</param> /// <param name="buffer">data, corresponded with the request code.</param> /// <returns> /// The result of Task contains a length of bytes actually sent to the serial port. /// </returns> private Task<uint> UsbControlRequestForSet( uint index, Windows.Devices.Usb.UsbControlRequestType requestType, byte request, ushort value, Windows.Storage.Streams.IBuffer buffer ) { return Task.Run(async () => { var packet = new UsbSetupPacket(); packet.RequestType = requestType; packet.Request = request; packet.Value = value; packet.Length = buffer != null ? buffer.Length : 0; packet.Index = index; return await this.device.SendControlOutTransferAsync(packet, buffer); }); }
/// <summary> /// GET_LINE_CODING CDC request. /// </summary> /// <param name="index">Interface index.</param> /// <returns> /// The result of Task contains a buffer of Line Coding structure. /// </returns> private Task<Windows.Storage.Streams.IBuffer> GetLineCoding( uint index ) { return Task.Run(async () => { var buffer = new Windows.Storage.Streams.Buffer(Constants.ExpectedResultGetLineCoding); buffer.Length = Constants.ExpectedResultGetLineCoding; var requestType = new UsbControlRequestType(); requestType.AsByte = RequestType.Get; var packet = new UsbSetupPacket(); packet.RequestType = requestType; packet.Request = RequestCode.GetLineCoding; packet.Value = 0; packet.Length = buffer.Length; packet.Index = index; return await this.device.SendControlInTransferAsync(packet, buffer); }); }
/// <summary> /// Initiates a control transfer to set the blink pattern on the SuperMutt's LED. /// /// Any errors in async function will be passed down the task chain and will not be caught here because errors should be handled /// at the end of the task chain. /// /// Setting LED blink pattern require setup packet: /// bmRequestType: type: VENDOR /// recipient: DEVICE /// bRequest: 0x03 /// wValue: 0-7 (any number in that range, inclusive) /// wLength: 0 /// /// The SuperMutt has the following patterns: /// 0 - LED always on /// 1 - LED flash 2 seconds on, 2 off, repeat /// 2 - LED flash 2 seconds on, 1 off, 2 on, 4 off, repeat /// ... /// 7 - 7 iterations of 2 on, 1 off, followed by 4 off, repeat /// </summary> /// <param name="pattern">A number from 0-7. Each number represents a different blinking pattern</param> /// <returns>A task that can be used to chain more methods after completing the scenario</returns> async Task SetSuperMuttLedBlinkPatternAsync(Byte pattern) { UsbSetupPacket setupPacket = new UsbSetupPacket { RequestType = new UsbControlRequestType { Direction = UsbTransferDirection.Out, Recipient = UsbControlRecipient.Device, ControlTransferType = UsbControlTransferType.Vendor }, Request = SuperMutt.VendorCommand.SetLedBlinkPattern, Value = pattern, Length = 0 }; UInt32 bytesTransferred = await EventHandlerForDevice.Current.Device.SendControlOutTransferAsync(setupPacket); MainPage.Current.NotifyUser("The Led blink pattern is set to " + pattern.ToString(), NotifyType.StatusMessage); }