Пример #1
0
            /// <summary>
            /// Unloads the controller
            /// </summary>
            internal void Unload()
            {
                try
                {
                    if (ControllerDevice != null)
                    {
                        if (UnloadBuffer.Length > 0)
                        {
                            // Send unload buffer to turn off controller
                            int bytesWritten;
                            ControllerDevice.ControlTransfer(ref setupPacket, UnloadBuffer, UnloadBuffer.Length, out bytesWritten);
                        }
                        IUsbDevice wholeUsbDevice = ControllerDevice as IUsbDevice;
                        if (!ReferenceEquals(wholeUsbDevice, null))
                        {
                            // Release interface
                            wholeUsbDevice.ReleaseInterface(1);
                        }
                        ControllerDevice.Close();
                        UsbDevice.Exit();
                    }
                }
                catch
                {
                    //Only trying to unload
                }

                if (ControllerDevice != null)
                {
                }
            }
Пример #2
0
 public bool transfer_in(byte request, int value, ref byte[] data, int length, out int actual)
 {
   bool rval;
   UsbSetupPacket setup = new UsbSetupPacket(0xA1, request, value, DFUinterface, length);
   rval=myUSBDevice.ControlTransfer(ref setup, data, length, out actual);
   return(rval);
 }
Пример #3
0
        /// <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;
        }
Пример #4
0
        /// <summary>
        /// Set a GPIO pin high
        /// </summary>
        /// <param name="pin">Pin number</param>
        public void setPinHigh(byte pin)
        {
            byte[] buffer_    = new byte[8];
            int    whatIsThis = 8;

            MySetupPacket = new UsbSetupPacket(0xC0, 18, pin, 0, 8);
            MyUsbDevice.ControlTransfer(ref MySetupPacket, buffer_, 8, out whatIsThis);
        }
Пример #5
0
        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);
        }
Пример #6
0
        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");
            }
        }
Пример #7
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Зажигаем
            UsbSetupPacket packet = new UsbSetupPacket((byte)(UsbCtrlFlags.RequestType_Vendor | UsbCtrlFlags.Recipient_Device | UsbCtrlFlags.Direction_Out), 1, (short)1, 0, 0);
            int            countIn;

            byte[] data = new byte[1];
            MyUsbDevice.ControlTransfer(ref packet, data, 0, out countIn);
        }
Пример #8
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]);
        }
Пример #9
0
        public void sendPkt(UsbSetupPacket pkt)
        {
            int c;

            if (!device.ControlTransfer(ref pkt, null, 0, out c))
            {
                find();
                device.ControlTransfer(ref pkt, null, 0, out c);
            }
        }
        bool USB_ControlTransfer(byte request, int value = 0)
        {
            byte reqType = 0;

            reqType |= (byte)UsbRequestType.TypeVendor;
            reqType |= (byte)UsbRequestRecipient.RecipDevice;
            reqType |= (byte)UsbEndpointDirection.EndpointOut;
            var packet = new UsbSetupPacket(reqType, request, (short)value, 0, 0);

            object buf = null;

            return(_device.ControlTransfer(ref packet, buf, 0, out _));
        }
Пример #11
0
        private void ReadUsbEndpointIn(byte request, ref byte[] datain, int prog_address = 0, int prog_pagesize = 0, int prog_nbytes = 0)
        {
            byte reqType   = (byte)UsbRequestType.TypeVendor | (byte)UsbEndpointDirection.EndpointIn;
            var  packet    = new UsbSetupPacket(reqType, request, (short)prog_address, (short)prog_pagesize, (short)prog_nbytes);
            var  issuccess = _usbdevice.ControlTransfer(ref packet, datain, datain.Length, out _);

            if (!issuccess)
            {
                var str = string.Format("Failed to ControlTransfer USB UsbEndpointIn!\nError Code: {0} \n\n{1}",
                                        UsbDevice.LastErrorNumber, UsbDevice.LastErrorString);
                throw new Exception(str);
            }
        }
Пример #12
0
        bool uploadbyte(byte byte1, ushort index)
        {
            UsbSetupPacket pack = new UsbSetupPacket();

            pack.RequestType = (byte)UsbRequestType.TypeVendor;
            pack.Request     = 0x08;//USBRQ_HID_GET_REPORT谁便写个标记 和固件对上即可
            pack.Value       = byte1;
            pack.Index       = (short)index;
            pack.Length      = 8;
            int lengthTransferred = 0;

            return(MyUsbDevice.ControlTransfer(ref pack, IntPtr.Zero, 4, out lengthTransferred));
        }
Пример #13
0
        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
            {
            }
        }
Пример #14
0
        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);
        }
Пример #15
0
        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);
        }
Пример #16
0
        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.");
            }
        }
Пример #17
0
        private void _SendHCICommand(Opcode command, byte[] parameterData, bool returnImmediately)
        {
            var cmdData = new byte[3 + (parameterData != null ? parameterData.Length : 0)];
            var packet  = new UsbSetupPacket(0x20, 0x00, 0x0000, 0x0000, (short)cmdData.Length);

            cmdData[0] = (byte)(command.Data & 0xFF);
            cmdData[1] = (byte)((command.Data >> 8) & 0xFF);
            if (parameterData != null && parameterData.Length > 0)
            {
                cmdData[2] = (byte)parameterData.Length;
                for (int i = 0; i < parameterData.Length; i++)
                {
                    cmdData[3 + i] = parameterData[i];
                }
            }

            int transferred;

            _device.ControlTransfer(ref packet, cmdData, cmdData.Length, out transferred);
            if (transferred != cmdData.Length)
            {
                throw new InvalidOperationException(String.Format("Failed to send command; sent {0} bytes instead of {1}",
                                                                  transferred, cmdData.Length));
            }

            if (!returnImmediately)
            {
                //Wait for command to complete
                _WaitForCompletion(command);
            }
        }
Пример #18
0
        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);
        }
Пример #19
0
        /// <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];
            }

            if (_device != null)
            {
                // Send data and get the result
                if (_device.ControlTransfer(ref packet, buffer, buffer.Length, out transfered))
                {
                    result = true;
                }
            }


            return(result);
        }
Пример #20
0
        protected void ControlTransfer(UsbSetupPacket setupPacket, object buffer, int bufferLength)
        {
            if (buffer == null)
            {
                // workaround, only necessary on Linux
                buffer = new byte[1];
            }
            int retries = 0;

            do
            {
                int lengthTransferred;
                // check for transfer success:
                // 1. that the request isn't STALLed / NACKed
                // 2. that the correct number of bytes were received / transmitted
                if (device.ControlTransfer(ref setupPacket, buffer, bufferLength, out lengthTransferred) &&
                    (lengthTransferred == bufferLength))
                {
                    return;
                }
                // device/bus error, let's hope it's transitional only
                Thread.Sleep(10);
            } while (retries++ < 10);

            // elevate persistent error
            throw new ApplicationException(String.Format("Failed to perform control transfer ({0}) to target {1}", setupPacket, this));
        }
Пример #21
0
        public static void SendCtrl(byte[] Data, bool RawMode = false)
        {
            int transfered = 0;
            var usp        = new UsbSetupPacket(0x40, 0x09, 0x0301, 0x0000, 8);

            uDevice.ControlTransfer(ref usp, Data, 8, out transfered);
        }
        private void ControlTransferInternal(byte bRequest, int wValue, int wIndex)
        {
            var setupPkt = new UsbSetupPacket(0x40, bRequest, wValue, wIndex, 0);
            var retVal   = _usbDevice.ControlTransfer(setupPkt, Array.Empty <byte>(), 0, 0);

            if (retVal != 0)
            {
                throw new UsbException($"ControlTransfer returned non zero value {retVal}");
            }
        }
Пример #23
0
        public string GetStringDescriptor(byte index)
        {
            if (IsAvailable == false)
            {
                return(null);
            }

            var packet = new UsbSetupPacket((byte)UsbEndpointDirection.EndpointIn,
                                            (byte)UsbStandardRequest.GetDescriptor,
                                            (short)(0x0300 | index), // (usb.util.DESC_TYPE_STRING << 8) | index
                                            0,                       //Language ID
                                            255);                    //Length
            var byteArray = new byte[256];
            int numBytesTransferred;

            _usbDevice.ControlTransfer(ref packet, byteArray, byteArray.Length, out numBytesTransferred);

            return(Encoding.Unicode.GetString(byteArray));
        }
Пример #24
0
        //---------------------------------------------------------------------------------

        private static void Usbout(UsbDevice dev, byte data, byte ctrl)
        {
            int transferred = 0;

            byte[] dataBuffer = new byte[2] {
                data, ctrl
            };
            UsbSetupPacket UsbSetup = new UsbSetupPacket(32, 9, 0, 0, 0);

            dev.ControlTransfer(ref UsbSetup, dataBuffer, 8, out transferred);
        }
Пример #25
0
        public void sendControlPacket(Object source, ElapsedEventArgs e)
        {
            // Send the control packet (this is what keeps strumming alive)
            byte[] buffer = new byte[9] {
                0x02, 0x08, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
            };
            int            bytesWrote;
            UsbSetupPacket setupPacket = new UsbSetupPacket(0x21, 0x09, 0x0201, 0x0000, 0x0008);

            device.ControlTransfer(ref setupPacket, buffer, 0x0008, out bytesWrote);
        }
Пример #26
0
 private int SendCommand(CommandType type, int wValue, int wIndex, int wLength, byte[] data)
 {
     mvarDevice.ControlTransfer((byte)((byte)EndpointDirection.Out | (byte)RequestType.Vendor | (byte)RequestRecipient.Device),
                                (byte)type,
                                (ushort)wValue,
                                (ushort)wIndex,
                                data,
                                // (ushort)wLength,
                                2000);
     return(0);
 }
Пример #27
0
        private void button2_Click(object sender, EventArgs e)
        {
            MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder); //Чтение данныйх
            UsbSetupPacket packet = new UsbSetupPacket((byte)(UsbCtrlFlags.RequestType_Vendor | UsbCtrlFlags.Recipient_Device | UsbCtrlFlags.Direction_In), 2, (short)0, (short)0, (short)0);
            int            countIn;

            byte[] data = new byte[1];
            if (MyUsbDevice.ControlTransfer(ref packet, data, 1, out countIn) && (countIn == 1))
            {
                label3.Text = "Прочитано значние " + data[0].ToString();
            }
        }
Пример #28
0
        public override void SetLED(byte led, bool remember = false)
        {
            if (remember)
            {
                LED = led;
            }

            byte[]         buffer           = { 0, 0, led, 0, 0, 0, 0, 0 };
            UsbSetupPacket setupPacket      = new UsbSetupPacket(0x21, 9, 0x0200, 0x00, (short)buffer.Length);
            int            lengthTransfered = -1;

            usbDevice.ControlTransfer(ref setupPacket, buffer, buffer.Length, out lengthTransfered);
        }
Пример #29
0
        static private bool WriteData(byte request, ushort addr, byte[] data)
        {
            using (UsbDevice dev = OpenUSBDevice())
            {
                if (dev == null)
                {
                    return(false);
                }

                IntPtr buf = IntPtr.Zero;
                try
                {
                    // make send data
                    byte[] senddata = new byte[data.Length];
                    for (int i = 0; i < data.Length; i++)
                    {
                        senddata[i] = (byte)(data[i] ^ 0xA5);
                    }

                    buf = Marshal.AllocCoTaskMem(senddata.Length);
                    Marshal.Copy(senddata, 0, buf, senddata.Length);

                    int transferredlength = 0;

                    setupPacketOut.Request = (byte)request;
                    setupPacketOut.Value   = (short)addr;
                    setupPacketOut.Index   = 0;
                    setupPacketOut.Length  = (short)senddata.Length;

                    if (dev.ControlTransfer(ref setupPacketOut, buf, setupPacketOut.Length, out transferredlength))
                    {
                        if (transferredlength != senddata.Length)
                        {
                            return(false);
                        }

                        return(true);
                    }
                }
                finally
                {
                    if (buf != IntPtr.Zero)
                    {
                        Marshal.FreeCoTaskMem(buf);
                    }
                }
            }

            return(false);
        }
Пример #30
0
        protected void SendCMD(Commands cmd, uint argA = 0, uint argB = 0)
        {
            CheckDeviceState();
            Main.SendDebug(String.Format("Sending CMD: {0} (0x{0:X}) 0x{1:X08} 0x{2:X08}", cmd, argA, argB));
            var buf = BitConverter.GetBytes(argA);
            var tmp = BitConverter.GetBytes(argB);

            Array.Resize(ref buf, buf.Length + tmp.Length);
            Array.Copy(tmp, 0, buf, buf.Length - tmp.Length, tmp.Length);
            var packet = new UsbSetupPacket((byte)UsbRequestType.TypeVendor, (byte)cmd, 0, 0, 0);
            int sent;

            Device.ControlTransfer(ref packet, buf, buf.Length, out sent);
        }