Пример #1
0
        public static byte[] ReceiveVendorResponse(CyUSBDevice usbDevice, MonoUsbDeviceHandle monoDeviceHandle, byte reqCode, int length, ushort value = 0, ushort index = 0)
        {
            if (usbDevice != null)
            {
                CyControlEndPoint ctrlEpt = usbDevice.ControlEndPt;
                ctrlEpt.TimeOut   = TIMEOUT;
                ctrlEpt.Direction = CyConst.DIR_FROM_DEVICE;
                ctrlEpt.ReqType   = CyConst.REQ_VENDOR;
                ctrlEpt.Target    = CyConst.TGT_DEVICE;
                ctrlEpt.ReqCode   = reqCode;
                ctrlEpt.Value     = value;
                ctrlEpt.Index     = index;

                int    bytes  = length;
                byte[] buffer = new byte[bytes];
                ctrlEpt.XferData(ref buffer, ref bytes);
                if (bytes == buffer.Length)
                {
                    return(buffer);
                }
            }
            else
            {
                short  bytes       = (short)length;
                byte[] data        = new byte[bytes];
                byte   requestType = CyConst.DIR_FROM_DEVICE + CyConst.REQ_VENDOR + CyConst.TGT_DEVICE;
                int    ret         = MonoUsbApi.ControlTransfer(monoDeviceHandle, requestType, reqCode, (short)value, (short)index, data, bytes, TIMEOUT);
                if (ret == data.Length)
                {
                    return(data);
                }
            }

            return(null);
        }
Пример #2
0
        public static bool SendVendorRequest(CyUSBDevice usbDevice, MonoUsbDeviceHandle monoDeviceHandle, byte reqCode, byte[] data, ushort value = 0, ushort index = 0)
        {
            if (data == null)
            {
                data = new byte[0];
            }

            if (usbDevice != null)
            {
                CyControlEndPoint ctrlEpt = usbDevice.ControlEndPt;
                ctrlEpt.TimeOut   = TIMEOUT;
                ctrlEpt.Direction = CyConst.DIR_TO_DEVICE;
                ctrlEpt.ReqType   = CyConst.REQ_VENDOR;
                ctrlEpt.Target    = CyConst.TGT_DEVICE;
                ctrlEpt.ReqCode   = reqCode;
                ctrlEpt.Value     = value;
                ctrlEpt.Index     = index;

                int bytes = data.Length;
                ctrlEpt.XferData(ref data, ref bytes);
                return(bytes == data.Length);
            }
            else
            {
                short bytes       = (short)data.Length;
                byte  requestType = CyConst.DIR_TO_DEVICE + CyConst.REQ_VENDOR + CyConst.TGT_DEVICE;
                int   ret         = MonoUsbApi.ControlTransfer(monoDeviceHandle, requestType, reqCode, (short)value, (short)index, data, bytes, TIMEOUT);
                return(ret == data.Length);
            }
        }
Пример #3
0
        private static void TurnOff(MonoUsbDeviceHandle rapidradio)
        {
            var cmdParams = new Params {
                Mode = RadioMode.Idle
            };
            var settings = cmdParams.Serialize();

            SendData(rapidradio, 4, settings, settings.Length, 1000);
        }
        private static int libusb_control_transfer(MonoUsbDeviceHandle deviceHandle, MonoUsbControlSetupHandle controlSetupHandle, int timeout)
        {
            MonoUsbTransfer  transfer        = MonoUsbTransfer.Alloc(0);
            ManualResetEvent completeEvent   = new ManualResetEvent(false);
            GCHandle         gcCompleteEvent = GCHandle.Alloc(completeEvent);

            transfer.FillControl(deviceHandle, controlSetupHandle, controlTransferDelegate, GCHandle.ToIntPtr(gcCompleteEvent), timeout);

            int r = (int)transfer.Submit();

            if (r < 0)
            {
                transfer.Free();
                gcCompleteEvent.Free();
                return(r);
            }

            while (!completeEvent.WaitOne(0, false))
            {
                r = MonoUsbApi.HandleEvents(sessionHandle);
                if (r < 0)
                {
                    if (r == (int)MonoUsbError.ErrorInterrupted)
                    {
                        continue;
                    }
                    transfer.Cancel();
                    while (!completeEvent.WaitOne(0, false))
                    {
                        if (MonoUsbApi.HandleEvents(sessionHandle) < 0)
                        {
                            break;
                        }
                    }
                    transfer.Free();
                    gcCompleteEvent.Free();
                    return(r);
                }
            }

            if (transfer.Status == MonoUsbTansferStatus.TransferCompleted)
            {
                r = transfer.ActualLength;
            }
            else
            {
                r = (int)MonoUsbApi.MonoLibUsbErrorFromTransferStatus(transfer.Status);
            }

            transfer.Free();
            gcCompleteEvent.Free();
            return(r);
        }
Пример #5
0
        static void config_op(MonoUsbDeviceHandle handle, byte endpoint, byte[] data, int readcnt)
        {
            int actual_length = 0;
            int res;

            byte[] recv_buf = new byte[1024];

            GCHandle data_gc     = GCHandle.Alloc(data, GCHandleType.Pinned);
            GCHandle recv_buf_gc = GCHandle.Alloc(recv_buf, GCHandleType.Pinned);

            MonoUsbTransferDelegate d = noop_usb_callback;

            MonoUsbTransfer transfer = new MonoUsbTransfer(0);

            wait = 0;

            Console.WriteLine("data_gc addr = {0}", data_gc.AddrOfPinnedObject());
            Console.WriteLine("recv_buf_gc addr = {0}", recv_buf_gc.AddrOfPinnedObject());

            // Execute the write operation (asynchronous).
            transfer.FillBulk(handle, endpoint, data_gc.AddrOfPinnedObject(), data.Length, d, recv_buf_gc.AddrOfPinnedObject(), 4000);
            transfer.Submit();

            Thread.Sleep(300);

            // Execute the specified number of read operations (synchronous).
            for (int x = 0; x < readcnt; ++x)
            {
                res = Usb.BulkTransfer(handle, (byte)(endpoint | 0x80), recv_buf_gc.AddrOfPinnedObject(), recv_buf.Length, out actual_length, 4000);
                if (res != 0)
                {
                    throw new Exception("config_op Usb.BulkTransfer failure");
                }
                // Should only be here once the above transfer completes.
            }

            // Wait for the first write asynchronous to return.
            // Do not poll forever. Abort if it takes too long.
            var st = DateTime.Now;

            if (readcnt > 0)
            {
                while (wait == 0 && (DateTime.Now - st).TotalSeconds < 30)
                {
                    Thread.Sleep(100);
                }
            }

            data_gc.Free();
            recv_buf_gc.Free();
        }
Пример #6
0
        /// <summary>
        /// Helper function to populate the required <see cref="MonoUsbTransfer"/> properties for a control transfer.
        /// </summary>
        /// <remarks>
        /// <note type="tip">
        /// <para>Isochronous transfers are not supported on windows.</para>
        /// </note>
        /// <note title="Libusb-1.0 API Note:" type="cpp">
        /// <see cref="FillControl"/> is similar to
        /// <a href="http://libusb.sourceforge.net/api-1.0/group__asyncio.html#ga3a8513ed87229fe2c9771ef0bf17206e">libusb_fill_control_transfer()</a>.
        /// </note>
        /// </remarks>
        /// <param name="devHandle">handle of the device that will handle the transfer</param>
        /// <param name="controlSetupHandle">the setup packet/control data to transfer.</param>
        /// <param name="callback">callback function to be invoked on transfer completion</param>
        /// <param name="userData">user data to pass to callback function</param>
        /// <param name="timeout">timeout for the transfer in milliseconds</param>
        public void FillControl(MonoUsbDeviceHandle devHandle, MonoUsbControlSetupHandle controlSetupHandle, Delegate callback, IntPtr userData, int timeout)
        {
            PtrDeviceHandle = devHandle.DangerousGetHandle();
            Endpoint        = 0;
            PtrCallbackFn   = Marshal.GetFunctionPointerForDelegate(callback);
            PtrUserData     = userData;
            Timeout         = timeout;
            Type            = EndpointType.Control;
            Flags           = MonoUsbTransferFlags.None;

            IntPtr pSetupPacket = controlSetupHandle.DangerousGetHandle();

            PtrBuffer = pSetupPacket;
            MonoUsbControlSetup w = new MonoUsbControlSetup(pSetupPacket);

            Length = MonoUsbControlSetup.SETUP_PACKET_SIZE + w.Length;
        }
Пример #7
0
        private static void SendData(MonoUsbDeviceHandle rapidradio, int endpoint, byte[] data, int length, int timeout = 1000000)
        {
            Marshal.Copy(data, 0, _unmanagedWriteBuff, Math.Min(length, 32));

            int transferred;
            var r = MonoUsbApi.BulkTransfer(rapidradio,
                                            (byte)endpoint,
                                            _unmanagedWriteBuff,
                                            length,
                                            out transferred,
                                            timeout);

            if (r != (int)MonoUsbError.Success)
            {
                throw new Exception("Error while sending: " + GetErrorMessage(r));
            }
        }
Пример #8
0
 /// <summary>
 /// Helper function to populate the required <see cref="MonoUsbTransfer"/> properties for an interrupt transfer.
 /// </summary>
 /// <remarks>
 /// <note title="Libusb-1.0 API Note:" type="cpp">
 /// <see cref="FillInterrupt"/> is roughly equivalent to
 /// <a href="http://libusb.sourceforge.net/api-1.0/group__asyncio.html#ga90f53cea1124a7566df1aa1202b77510">libusb_fill_interrupt_transfer()</a>.
 /// </note>
 /// </remarks>
 /// <param name="devHandle">handle of the device that will handle the transfer</param>
 /// <param name="endpoint">address of the endpoint where this transfer will be sent</param>
 /// <param name="buffer">data buffer</param>
 /// <param name="length">length of data buffer</param>
 /// <param name="callback">callback function to be invoked on transfer completion</param>
 /// <param name="userData">user data to pass to callback function</param>
 /// <param name="timeout">timeout for the transfer in milliseconds</param>
 public void FillInterrupt(MonoUsbDeviceHandle devHandle,
                           byte endpoint,
                           IntPtr buffer,
                           int length,
                           Delegate callback,
                           IntPtr userData,
                           int timeout)
 {
     PtrDeviceHandle = devHandle.DangerousGetHandle();
     Endpoint        = endpoint;
     PtrBuffer       = buffer;
     Length          = length;
     PtrCallbackFn   = Marshal.GetFunctionPointerForDelegate(callback);
     PtrUserData     = userData;
     Timeout         = timeout;
     Type            = EndpointType.Interrupt;
     Flags           = MonoUsbTransferFlags.None;
 }
Пример #9
0
        private static int ReadData(MonoUsbDeviceHandle rapidradio, int endpoint, byte[] data, int length, int timeout = 1)
        {
            int transferred;
            var r = MonoUsbApi.BulkTransfer(rapidradio,
                                            (byte)(endpoint + 0x80),
                                            _unmanagedReadBuff,
                                            length,
                                            out transferred,
                                            timeout);

            if (r != (int)MonoUsbError.Success && r != (int)MonoUsbError.ErrorTimeout)
            {
                throw new Exception("Error while reading: " + GetErrorMessage(r));
            }

            Marshal.Copy(_unmanagedReadBuff, data, 0, Math.Min(transferred, 32));

            return(transferred);
        }
Пример #10
0
        ///<summary>
        /// Opens the USB device handle.
        ///</summary>
        ///<returns>
        ///True if the device is already opened or was opened successfully.
        ///False if the device does not exists or is no longer valid.
        ///</returns>
        public override bool Open()
        {
            if (IsOpen)
            {
                return(true);
            }
            MonoUsbDeviceHandle handle = new MonoUsbDeviceHandle(mMonoUSBProfile.ProfileHandle);

            if (handle.IsInvalid)
            {
                UsbError.Error(ErrorCode.MonoApiError, (int)MonoUsbDeviceHandle.LastErrorCode, "MonoUsbDevice.Open Failed", this);
                mUsbHandle = null;
                return(false);
            }
            mUsbHandle = handle;
            if (IsOpen)
            {
                return(true);
            }

            mUsbHandle.Close();
            return(false);
        }
Пример #11
0
        public static int Main(string[] args)
        {
            MonoUsbDeviceHandle device_handle = null;

            int r = 0;
            int transferred;

            byte[] testWriteData = new byte[TEST_WRITE_LEN];
            byte[] testReadData  = new byte[TEST_READ_LEN];

            if (args.Length > 0)
            {
                switch (args[0].ToLower())
                {
                case "sync":
                    TEST_MODE = TestMode.Sync;
                    break;

                case "async":
                    TEST_MODE = TestMode.Async;
                    break;
                }
            }

            fillTestData(testWriteData, TEST_WRITE_LEN);
            memset(testReadData, 0, TEST_READ_LEN);

            int loopCount = 0;

            do
            {
                try
                {
                    do
                    {
                        sessionHandle = new MonoUsbSessionHandle();
                        if (sessionHandle.IsInvalid)
                        {
                            throw new Exception("Invalid session handle.");
                        }

                        Console.WriteLine("Opening Device..");
                        device_handle = MonoUsbApi.OpenDeviceWithVidPid(sessionHandle, MY_VID, MY_PID);
                        if ((device_handle == null) || device_handle.IsInvalid)
                        {
                            break;
                        }

                        // If TEST_REST_DEVICE = True, reset the device and re-open
                        if (TEST_REST_DEVICE)
                        {
                            MonoUsbApi.ResetDevice(device_handle);
                            device_handle.Close();
                            device_handle = MonoUsbApi.OpenDeviceWithVidPid(sessionHandle, MY_VID, MY_PID);
                            if ((device_handle == null) || device_handle.IsInvalid)
                            {
                                break;
                            }
                        }

                        // Set configuration
                        Console.WriteLine("Set Config..");
                        r = MonoUsbApi.SetConfiguration(device_handle, MY_CONFIG);
                        if (r != 0)
                        {
                            break;
                        }

                        // Claim interface
                        Console.WriteLine("Set Interface..");
                        r = MonoUsbApi.ClaimInterface(device_handle, MY_INTERFACE);
                        if (r != 0)
                        {
                            break;
                        }

                        /////////////////////
                        // Write test data //
                        /////////////////////
                        int packetCount      = 0;
                        int transferredTotal = 0;
                        do
                        {
                            Console.WriteLine("Sending test data..");

                            // If the Async TEST_MODE enumeration is set, use
                            // the internal transfer function
                            if (TEST_MODE == TestMode.Async)
                            {
                                r = (int)doBulkAsyncTransfer(device_handle,
                                                             MY_EP_WRITE,
                                                             testWriteData,
                                                             TEST_WRITE_LEN,
                                                             out transferred,
                                                             MY_TIMEOUT);
                            }
                            else
                            {
                                // Use the sync bulk transfer API function
                                r = MonoUsbApi.BulkTransfer(device_handle,
                                                            MY_EP_WRITE,
                                                            testWriteData,
                                                            TEST_WRITE_LEN,
                                                            out transferred,
                                                            MY_TIMEOUT);
                            }
                            if (r == 0)
                            {
                                packetCount++;
                                transferredTotal += transferred;
                            }
                            // Keep writing data until an error occurs or
                            // 4 packets have been sent.
                        } while (r == 0 && packetCount < 5);


                        if (r == (int)MonoUsbError.ErrorTimeout)
                        {
                            // This is considered normal operation
                            Console.WriteLine("Write Timed Out. {0} packet(s) written ({1} bytes)", packetCount, transferredTotal);
                        }
                        else if (r != (int)MonoUsbError.ErrorTimeout && r != 0)
                        {
                            // An error, other than ErrorTimeout was received.
                            Console.WriteLine("Write failed:{0}", (MonoUsbError)r);
                            break;
                        }
                        ////////////////////
                        // Read test data //
                        ////////////////////
                        Console.WriteLine("Reading test data..");
                        packetCount      = 0;
                        transferredTotal = 0;
                        do
                        {
                            // If the Async TEST_MODE enumeration is set, use
                            // the internal transfer function
                            if (TEST_MODE == TestMode.Async)
                            {
                                r = (int)doBulkAsyncTransfer(device_handle,
                                                             MY_EP_READ,
                                                             testReadData,
                                                             TEST_READ_LEN,
                                                             out transferred,
                                                             MY_TIMEOUT);
                            }
                            else
                            {
                                // Use the sync bulk transfer API function
                                r = MonoUsbApi.BulkTransfer(device_handle,
                                                            MY_EP_READ,
                                                            testReadData,
                                                            TEST_READ_LEN,
                                                            out transferred,
                                                            MY_TIMEOUT);
                            }
                            if (r == (int)MonoUsbError.ErrorTimeout)
                            {
                                // This is considered normal operation
                                Console.WriteLine("Read Timed Out. {0} packet(s) read ({1} bytes)", packetCount, transferredTotal);
                            }
                            else if (r != 0)
                            {
                                // An error, other than ErrorTimeout was received.
                                Console.WriteLine("Read failed:{0}", (MonoUsbError)r);
                            }
                            else
                            {
                                transferredTotal += transferred;
                                packetCount++;

                                // Display test data.
                                Console.Write("Received: ");
                                Console.WriteLine(System.Text.Encoding.Default.GetString(testReadData, 0, transferred));
                            }
                            // Keep reading data until an error occurs, (ErrorTimeout)
                        } while (r == 0);
                    } while (false);
                }
                finally
                {
                    // Free and close resources
                    if (device_handle != null)
                    {
                        if (!device_handle.IsInvalid)
                        {
                            MonoUsbApi.ReleaseInterface(device_handle, MY_INTERFACE);
                            device_handle.Close();
                        }
                    }
                    if (sessionHandle != null)
                    {
                        sessionHandle.Close();
                        sessionHandle = null;
                    }
                }
                // Run the entire test TEST_LOOP_COUNT times.
            } while (++loopCount < TEST_LOOP_COUNT);

            Console.WriteLine("\nDone!  [Press any key to exit]");
            Console.ReadKey();

            return(r);
        }
Пример #12
0
        // This function originated from do_sync_bulk_transfer()
        // in sync.c of the Libusb-1.0 source code.
        private static MonoUsbError doBulkAsyncTransfer(MonoUsbDeviceHandle dev_handle,
                                                          byte endpoint,
                                                          byte[] buffer,
                                                          int length,
                                                          out int transferred,
                                                          int timeout)
        {
            transferred = 0;
            MonoUsbTransfer transfer = new MonoUsbTransfer(0);
            if (transfer.IsInvalid) return MonoUsbError.ErrorNoMem;

            MonoUsbTransferDelegate monoUsbTransferCallbackDelegate = bulkTransferCB;
            int[] userCompleted = new int[] {0};
            GCHandle gcUserCompleted = GCHandle.Alloc(userCompleted, GCHandleType.Pinned);

            MonoUsbError e;
            GCHandle gcBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned);
            transfer.FillBulk(
                dev_handle,
                endpoint,
                gcBuffer.AddrOfPinnedObject(),
                length,
                monoUsbTransferCallbackDelegate,
                gcUserCompleted.AddrOfPinnedObject(),
                timeout);

            e = transfer.Submit();
            if ((int) e < 0)
            {
                transfer.Free();
                gcUserCompleted.Free();
                return e;
            }
            int r;
            Console.WriteLine("Transfer Submitted..");
            while (userCompleted[0] == 0)
            {
                e = (MonoUsbError) (r = Usb.HandleEvents(sessionHandle));
                if (r < 0)
                {
                    if (e == MonoUsbError.ErrorInterrupted)
                        continue;
                    transfer.Cancel();
                    while (userCompleted[0] == 0)
                        if (Usb.HandleEvents(sessionHandle) < 0)
                            break;
                    transfer.Free();
                    gcUserCompleted.Free();
                    return e;
                }
            }

            transferred = transfer.ActualLength;
            e = MonoUsbApi.MonoLibUsbErrorFromTransferStatus(transfer.Status);
            transfer.Free();
            gcUserCompleted.Free();
            return e;
        }
Пример #13
0
        /// <summary>
        /// Helper function to populate the required <see cref="MonoUsbTransfer"/> properties for a control transfer.
        /// </summary>
        /// <remarks>
        /// <note type="tip">
        /// <para>Isochronous transfers are not supported on windows.</para>
        /// </note>
        /// <note title="Libusb-1.0 API Note:" type="cpp">
        /// <see cref="FillControl"/> is similar to
        /// <a href="http://libusb.sourceforge.net/api-1.0/group__asyncio.html#ga3a8513ed87229fe2c9771ef0bf17206e">libusb_fill_control_transfer()</a>.
        /// </note>
        /// </remarks>
        /// <param name="devHandle">handle of the device that will handle the transfer</param>
        /// <param name="controlSetupHandle">the setup packet/control data to transfer.</param>
        /// <param name="callback">callback function to be invoked on transfer completion</param>
        /// <param name="userData">user data to pass to callback function</param>
        /// <param name="timeout">timeout for the transfer in milliseconds</param>
        public void FillControl(MonoUsbDeviceHandle devHandle, MonoUsbControlSetupHandle controlSetupHandle, Delegate callback, IntPtr userData, int timeout) 
        {
            PtrDeviceHandle = devHandle.DangerousGetHandle();
            Endpoint = 0;
            PtrCallbackFn = Marshal.GetFunctionPointerForDelegate(callback);
            PtrUserData = userData;
            Timeout = timeout;
            Type = EndpointType.Control;
            Flags = MonoUsbTransferFlags.None;

            IntPtr pSetupPacket = controlSetupHandle.DangerousGetHandle();
            PtrBuffer = pSetupPacket;
            MonoUsbControlSetup w = new MonoUsbControlSetup(pSetupPacket);
            Length = MonoUsbControlSetup.SETUP_PACKET_SIZE + w.Length;
        }
Пример #14
0
 /// <summary>
 /// Helper function to populate the required <see cref="MonoUsbTransfer"/> properties for an isochronous transfer.
 /// </summary>
 /// <remarks>
 /// <note type="tip">
 /// <para>Isochronous transfers are not supported on windows.</para>
 /// </note>
 /// <note title="Libusb-1.0 API Note:" type="cpp">
 /// <see cref="FillIsochronous"/> is similar to
 /// <a href="http://libusb.sourceforge.net/api-1.0/group__asyncio.html#ga30fdce8c461e851f0aa4c851014e1aa7">libusb_fill_iso_transfer()</a>.
 /// </note>
 /// </remarks>
 /// <param name="devHandle">handle of the device that will handle the transfer</param>
 /// <param name="endpoint">address of the endpoint where this transfer will be sent</param>
 /// <param name="buffer">data buffer</param>
 /// <param name="length">length of data buffer</param>
 /// <param name="numIsoPackets">the number of isochronous packets</param>
 /// <param name="callback">callback function to be invoked on transfer completion</param>
 /// <param name="userData">user data to pass to callback function</param>
 /// <param name="timeout">timeout for the transfer in milliseconds</param>
 public void FillIsochronous(MonoUsbDeviceHandle devHandle,
          byte endpoint,
          IntPtr buffer,
          int length,int numIsoPackets,
          Delegate callback,
          IntPtr userData,
          int timeout)
 {
     PtrDeviceHandle = devHandle.DangerousGetHandle();
     Endpoint = endpoint;
     PtrBuffer = buffer;
     Length = length;
     PtrCallbackFn = Marshal.GetFunctionPointerForDelegate(callback);
     PtrUserData = userData;
     Timeout = timeout;
     Type = EndpointType.Isochronous;
     Flags = MonoUsbTransferFlags.None;
     NumIsoPackets = numIsoPackets;
 }
Пример #15
0
 private static void StartReadingThread(MonoUsbDeviceHandle rapidradio)
 {
     _readingThread = new Thread(ReadFromUsbAndFlushToOutput);
     _readingThread.Start(rapidradio);
 }
Пример #16
0
        public static void ShowConfig(RichTextBox rtb)
        {
            // Initialize the context.
            sessionHandle = new MonoUsbSessionHandle();
            if (sessionHandle.IsInvalid)
            {
                throw new Exception(String.Format("Failed intialized libusb context.\n{0}:{1}",
                                                  MonoUsbSessionHandle.LastErrorCode,
                                                  MonoUsbSessionHandle.LastErrorString));
            }

            MonoUsbProfileList profileList = new MonoUsbProfileList();

            // The list is initially empty.
            // Each time refresh is called the list contents are updated.
            int ret = profileList.Refresh(sessionHandle);

            if (ret < 0)
            {
                throw new Exception("Failed to retrieve device list.");
            }
            rtb.AppendText(string.Format("{0} device(s) found.\r\n", ret));

            // Use the GetList() method to get a generic List of MonoUsbProfiles
            // Find all profiles that match in the MyVidPidPredicate.
            List <MonoUsbProfile> myVidPidList = profileList.GetList().FindAll(MyVidPidPredicate);

            // myVidPidList reresents a list of connected USB devices that matched
            // in MyVidPidPredicate.
            foreach (MonoUsbProfile profile in myVidPidList)
            {
                MonoUsbDeviceHandle h = profile.OpenDeviceHandle();// Usb.OpenDeviceWithVidPid(sessionHandle, 0x1915, 0x007B);

                if (h.IsInvalid)
                {
                    throw new Exception(string.Format("Failed opening device handle.\r\n{0}: {1}",
                                                      MonoUsbDeviceHandle.LastErrorCode,
                                                      MonoUsbDeviceHandle.LastErrorString));
                }

                Usb.SetConfiguration(h, 1);
                Usb.ClaimInterface(h, 1);
                MonoUsbProfileHandle ph = Usb.GetDevice(h);
                int packetSize          = Usb.GetMaxIsoPacketSize(ph, 0x88);



                // Write the VendorID and ProductID to console output.
                rtb.AppendText(string.Format("[Device] Vid:{0:X4} Pid:{1:X4}\r\n", profile.DeviceDescriptor.VendorID, profile.DeviceDescriptor.ProductID));

                // Loop through all of the devices configurations.
                for (byte i = 0; i < profile.DeviceDescriptor.ConfigurationCount; i++)
                {
                    // Get a handle to the configuration.
                    MonoUsbConfigHandle configHandle;
                    if (MonoUsbApi.GetConfigDescriptor(profile.ProfileHandle, i, out configHandle) < 0)
                    {
                        continue;
                    }
                    if (configHandle.IsInvalid)
                    {
                        continue;
                    }

                    // Create a MonoUsbConfigDescriptor instance for this config handle.
                    MonoUsbConfigDescriptor configDescriptor = new MonoUsbConfigDescriptor(configHandle);

                    // Write the bConfigurationValue to console output.
                    rtb.AppendText(string.Format("  [Config] bConfigurationValue:{0}\r\n", configDescriptor.bConfigurationValue));

                    // Interate through the InterfaceList
                    foreach (MonoUsbInterface usbInterface in configDescriptor.InterfaceList)
                    {
                        // Interate through the AltInterfaceList
                        foreach (MonoUsbAltInterfaceDescriptor usbAltInterface in usbInterface.AltInterfaceList)
                        {
                            // Write the bInterfaceNumber and bAlternateSetting to console output.
                            rtb.AppendText(string.Format("    [Interface] bInterfaceNumber:{0} bAlternateSetting:{1}\r\n",
                                                         usbAltInterface.bInterfaceNumber,
                                                         usbAltInterface.bAlternateSetting));

                            // Interate through the EndpointList
                            foreach (MonoUsbEndpointDescriptor endpoint in usbAltInterface.EndpointList)
                            {
                                // Write the bEndpointAddress, EndpointType, and wMaxPacketSize to console output.
                                rtb.AppendText(string.Format("      [Endpoint] bEndpointAddress:{0:X2} EndpointType:{1} wMaxPacketSize:{2}\r\n",
                                                             endpoint.bEndpointAddress,
                                                             (EndpointType)(endpoint.bmAttributes & 0x3),
                                                             endpoint.wMaxPacketSize));

                                if (endpoint.bEndpointAddress == 0x88)
                                {
                                }
                            }
                        }
                    }
                    // Not neccessary, but good programming practice.
                    configHandle.Close();
                }
            }
            // Not neccessary, but good programming practice.
            profileList.Close();
            // Not neccessary, but good programming practice.
            sessionHandle.Close();
        }
Пример #17
0
 public MonoAvalonPacket(MonoUsbDeviceHandle deviceHandle)
     : base()
 {
     this.deviceHandle = deviceHandle;
 }
Пример #18
0
        public bool DiscoveryUsbDevice(Boolean assignFlag = false)
        {
            UsbRegDeviceList allDevices = UsbDevice.AllDevices;

            if (assignFlag)
            {
                profileList   = new MonoUsbProfileList();
                sessionHandle = new MonoUsbSessionHandle();

                if (sessionHandle.IsInvalid)
                {
                    throw new Exception(String.Format("libusb {0}:{1}", MonoUsbSessionHandle.LastErrorCode,
                                                      MonoUsbSessionHandle.LastErrorString));
                }
                MyUsbDeviceArray = new UsbDevice[MAX_USB_DEVICE_COUNT];
            }
            else
            {
            }

            foreach (UsbRegistry usbRegistry in allDevices)
            {
                System.Console.WriteLine("Open one more ");
                if (usbRegistry.Open(out MyUsbDevice))
                {
                    if ((bt_vid == MyUsbDevice.Info.Descriptor.VendorID) && (bt_pid == MyUsbDevice.Info.Descriptor.ProductID))
                    {
                        MyUsbDeviceArray[UsbDeviceCount] = MyUsbDevice;
                        UsbDeviceCount++;
                    }
                    else
                    {
                        System.Console.WriteLine(String.Format("device vid {0} pid {1}", MyUsbDevice.Info.Descriptor.VendorID, MyUsbDevice.Info.Descriptor.ProductID));
                    }

                    for (int iConfig = 0; iConfig < MyUsbDevice.Configs.Count; iConfig++)
                    {
                        UsbConfigInfo configInfo = MyUsbDevice.Configs[iConfig];
                        Console.WriteLine(configInfo.ToString());
                    }
                }
            }

            System.Console.WriteLine(String.Format("Open  {0}", UsbDeviceCount));

            System.Console.WriteLine("begin");
            if (profileList != null)
            {
                profileList.Refresh(sessionHandle);
            }

            MonoUsbProfile myProfile = profileList.GetList().Find(MyVidPidPredicate);

            MatchingUsbDeviceList = profileList.GetList().FindAll(MyVidPidPredicate);

            if (myProfile == null)
            {
                Console.WriteLine("myProfile is 0");
                return(false);
            }

            // Open the device handle to perfom I/O
            myDeviceHandle = myProfile.OpenDeviceHandle();
            if (myDeviceHandle.IsInvalid)
            {
                throw new Exception(String.Format("{0}, {1}", MonoUsbDeviceHandle.LastErrorCode,
                                                  MonoUsbDeviceHandle.LastErrorString));
            }

            for (int i = 0; i < UsbDeviceCount; i++)
            {
                object thisHubPort;
                int    thisPortNum     = -1;
                int    thisHubNum      = -1;
                char[] separatingChars = { '_', '.', '#' };

                MyUsbDeviceArray[i].UsbRegistryInfo.DeviceProperties.TryGetValue("LocationInformation", out thisHubPort);

                System.Console.WriteLine(String.Format("thisHubPort {0}", thisHubPort));
                string[] words = thisHubPort.ToString().Split(separatingChars, System.StringSplitOptions.RemoveEmptyEntries);

                if (words[0].Equals("Port"))
                {
                    thisPortNum = Convert.ToInt32(words[1]);
                }
                if (words[2].Equals("Hub"))
                {
                    thisHubNum = Convert.ToInt32(words[3]);
                }

                if (assignFlag)
                {
                    usbDeviceInfo             = new UsbDeviceInfo();
                    usbDeviceInfo.MyUsbDevice = MyUsbDeviceArray[i];
                    usbDeviceInfo.Port        = thisPortNum;
                    usbDeviceInfo.Hub         = thisHubNum;
                    Console.WriteLine(String.Format("info {0},{1}", thisPortNum, thisHubNum));
                    FinalDeviceIndex = (short)i;
                }
                else
                {
                    if ((usb_port == thisPortNum) && (usb_hub == thisHubNum))
                    {
                        System.Console.WriteLine(String.Format("usb_port {0}, usb_hub {1}", usb_port, usb_hub));
                        FinalDeviceIndex = (short)i;
                        break;
                    }
                }
            }

            return(true);
        }
Пример #19
0
        private bool SetConfigUsbDevice()
        {
            int ret;

            if (FinalDeviceIndex == -1)
            {
                throw new Exception("No valid device index exists. Discovery of device wasnot successful.");
            }

            if (false)
            {
                try{
                    MyUsbDevice = MyUsbDeviceArray[FinalDeviceIndex];

                    if (MyUsbDevice == null)
                    {
                        throw new Exception("Device not found");
                    }

                    IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                    if (!ReferenceEquals(wholeUsbDevice, null))
                    {
                        // Select config #1
                        wholeUsbDevice.SetConfiguration(1);
                        wholeUsbDevice.ClaimInterface(0);
                    }

                    // open read endpoint 1
                    UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);
                    globalReader = reader;
                }
                catch (Exception ex) {
                    Console.WriteLine(ex);
                }
            }

            MonoUsbError e;

            myDeviceHandle = MatchingUsbDeviceList[FinalDeviceIndex].OpenDeviceHandle();

            if (myDeviceHandle == null || myDeviceHandle.IsInvalid)
            {
                throw new Exception(String.Format("Device not open previously {0}:{1}",
                                                  MonoUsbDeviceHandle.LastErrorCode,
                                                  MonoUsbDeviceHandle.LastErrorString
                                                  ));
            }


            // set configuration
            e = (MonoUsbError)(ret = MonoUsbApi.SetConfiguration(myDeviceHandle, 1));
            if (ret < 0)
            {
                throw new Exception(String.Format("Failed SetConfiguration. {0}:{1}", e, MonoUsbApi.StrError(e)));
            }
            ;;;
            // cliam interface
            e = (MonoUsbError)(ret = MonoUsbApi.ClaimInterface(myDeviceHandle, 0));
            if (ret < 0)
            {
                throw new Exception(String.Format("Failed ClaimInterface. {0}:{1}", e, MonoUsbApi.StrError(e)));
            }
            ;;;
            return(true);
        }
Пример #20
0
        void testComms()
        {
            if (profiles.Count < 1)
            {
                logger.info("testComms: no profiles");
                return;
            }

            foreach (MonoUsbProfile profile in profiles)
            {
                MonoUsbDeviceHandle device = null;
                try
                {
                    logger.info("Opening {0:x4}:{1:x4}", profile.DeviceDescriptor.VendorID, profile.DeviceDescriptor.ProductID);
                    device = profile.OpenDeviceHandle();
                    if (device.IsInvalid)
                    {
                        logger.error("Failed opening device handle: {0} ({1})", MonoUsbDeviceHandle.LastErrorCode, MonoUsbDeviceHandle.LastErrorString);
                        continue;
                    }

                    // re-confirm configurations for this profile
                    for (byte i = 0; i < profile.DeviceDescriptor.ConfigurationCount; i++)
                    {
                        MonoUsbConfigHandle configHandle;
                        if (MonoUsbApi.GetConfigDescriptor(profile.ProfileHandle, i, out configHandle) < 0)
                        {
                            continue;
                        }
                        if (configHandle.IsInvalid)
                        {
                            continue;
                        }
                        MonoUsbConfigDescriptor configDescriptor = new MonoUsbConfigDescriptor(configHandle);
                        logger.info("  configuration #{0}: {1} ({2})", i, configDescriptor.bConfigurationValue, configDescriptor);
                        logger.info("      type       = {0}", configDescriptor.bDescriptorType);
                        logger.info("      length     = {0}", configDescriptor.bLength);
                        logger.info("      attributes = {0:x2}", configDescriptor.bmAttributes);
                        logger.info("      interfaces = {0}", configDescriptor.bNumInterfaces);
                        logger.info("      extLength  = {0}", configDescriptor.ExtraLength);
                        logger.info("      iConfig    = {0}", configDescriptor.iConfiguration);
                        logger.info("      maxPower   = {0}", configDescriptor.MaxPower);
                        logger.info("      totalLength= {0}", configDescriptor.wTotalLength);
                    }

                    int result = 0;

                    // Set Configuration
                    // Note: http://libusb.sourceforge.net/api-1.0/caveats.html#configsel
                    MonoUsbError error = (MonoUsbError)(result = MonoUsbApi.SetConfiguration(device, 1));
                    if (false && result < 0)
                    {
                        logger.error("Failed SetConfiguration: {0} ({1}) (result = {2})", error, MonoUsbApi.StrError(error), result);
                        continue;
                    }

                    // Claim Interface
                    error = (MonoUsbError)(result = MonoUsbApi.ClaimInterface(device, 0));
                    if (result < 0)
                    {
                        logger.error("Failed ClaimInterface: {0} ({1})", error, MonoUsbApi.StrError(error));
                        continue;
                    }

                    // retain device handles
                    devices.Add(device);

                    byte DEVICE_TO_HOST      = 0xc0;
                    byte SECOND_TIER_COMMAND = 0xff;
                    byte GET_MODEL_CONFIG    = 0x01;
                    byte PAGE_SIZE           = 64;
                    byte PAGE_ID             = 0;
                    int  TIMEOUT_MS          = 1000;

                    // Create a vendor specific control setup, allocate 1 byte for return control data.
                    // byte requestType = (byte)(UsbCtrlFlags.Direction_In | UsbCtrlFlags.Recipient_Device | UsbCtrlFlags.RequestType_Vendor);
                    // byte request = 0x0F;
                    // MonoUsbControlSetupHandle controlSetupHandle = new MonoUsbControlSetupHandle(requestType, request, 0, 0, 1);

                    MonoUsbControlSetupHandle controlSetupHandle = new MonoUsbControlSetupHandle(DEVICE_TO_HOST, SECOND_TIER_COMMAND, GET_MODEL_CONFIG, PAGE_ID, PAGE_SIZE);

                    // Transfer the control setup packet
                    int len = libusb_control_transfer(device, controlSetupHandle, TIMEOUT_MS);
                    if (len > 0)
                    {
                        logger.info("Success");
                        byte[] ctrlDataBytes  = controlSetupHandle.ControlSetup.GetData(len);
                        string ctrlDataString = Helper.HexString(ctrlDataBytes, String.Empty, "h ");
                        logger.info("Return Length: {0}", len);
                        logger.info("DATA (hex)   : [ {0} ]", ctrlDataString.Trim());
                    }
                    MonoUsbApi.ReleaseInterface(device, 0);
                }
                finally
                {
                    if (device != null)
                    {
                        logger.info("closing device");
                        device.Close();
                    }
                }
            }
        }
Пример #21
0
        private void SendCommand(byte[] data, int duration)
        {
            MonoUsbProfileList  profileList    = new MonoUsbProfileList();
            MonoUsbDeviceHandle myDeviceHandle = null;

            try
            {
                // The list is initially empty.
                // Each time refresh is called the list contents are updated.
                profileList.Refresh(sessionHandle);

                // Use the GetList() method to get a generic List of MonoUsbProfiles
                // Find the first profile that matches in MyVidPidPredicate.
                MonoUsbProfile myProfile = profileList.GetList().Find(MyVidPidPredicate);
                if (myProfile == null)
                {
                    Console.WriteLine("Device not connected.");
                    return;
                }
                Console.WriteLine("Device connected.");
                // Open the device handle to perform I/O
                myDeviceHandle = myProfile.OpenDeviceHandle();
                if (myDeviceHandle.IsInvalid)
                {
                    throw new Exception(String.Format("Failed opening device handle.\n{0}:{1}",
                                                      MonoUsbDeviceHandle.LastErrorCode,
                                                      MonoUsbDeviceHandle.LastErrorString));
                }
                int          ret;
                MonoUsbError e;

                // Set Configuration
                e = (MonoUsbError)(ret = MonoUsbApi.SetConfiguration(myDeviceHandle, 1));
                if (ret < 0)
                {
                    throw new Exception(String.Format("Failed SetConfiguration.\n{0}:{1}", e, MonoUsbApi.StrError(e)));
                }

                // Claim Interface
                e = (MonoUsbError)(ret = MonoUsbApi.ClaimInterface(myDeviceHandle, 0));
                if (ret < 0)
                {
                    throw new Exception(String.Format("Failed ClaimInterface.\n{0}:{1}", e, MonoUsbApi.StrError(e)));
                }

                // Create a vendor specific control setup, allocate 1 byte for return control data.
                byte requestType = 0x40;// (byte)(UsbCtrlFlags.Direction_In | UsbCtrlFlags.Recipient_Device | UsbCtrlFlags.RequestType_Vendor);
                byte request     = 6;

                MonoUsbControlSetupHandle controlSetupHandle = new MonoUsbControlSetupHandle(requestType, request, 0x100, 0, data, 3);

                // Transfer the control setup packet
                ret = ControlTransfer(myDeviceHandle, controlSetupHandle, 1000);
                Thread.Sleep(duration);

                object data2 = new byte[] { 0, 0, 0 };
                MonoUsbControlSetupHandle controlSetupHandle2 = new MonoUsbControlSetupHandle(requestType, request, 0x100, 0, data2, 3);
                ret = ControlTransfer(myDeviceHandle, controlSetupHandle2, 1000);
                Thread.Sleep(500);
                if (ret > 0)
                {
                    Console.WriteLine("\nSuccess!\n");
                    byte[] ctrlDataBytes  = controlSetupHandle.ControlSetup.GetData(ret);
                    string ctrlDataString = Helper.HexString(ctrlDataBytes, String.Empty, "h ");
                    Console.WriteLine("Return Length: {0}", ret);
                    Console.WriteLine("DATA (hex)   : [ {0} ]\n", ctrlDataString.Trim());
                }
                MonoUsbApi.ReleaseInterface(myDeviceHandle, 0);
            }
            finally
            {
                profileList.Close();
                if (myDeviceHandle != null)
                {
                    myDeviceHandle.Close();
                }
                sessionHandle.Close();
                Console.WriteLine("End");
            }
        }
Пример #22
0
        private static void Listening(MonoUsbDeviceHandle rapidradio, Params cmdParams)
        {
            using (var stream = Console.OpenStandardOutput())
            {
                var  newline      = Encoding.ASCII.GetBytes(Environment.NewLine);
                byte packetNumber = 0;
                var  buff         = new byte[32];
                while (true)
                {
                    var read = ReadData(rapidradio, 3, buff, 32, 50);
                    if (read > 0)
                    {
                        if (read == 32 && TransmissionEndToken.SequenceEqual(buff))
                        {
                            // got transmission end token
                            break;
                        }

                        bool outputData = false;
                        if (cmdParams.PacketNumbering)
                        {
                            if (buff[0] > packetNumber)
                            {
                                if (cmdParams.Verbose)
                                {
                                    Error(string.Format("Lost packets, expected packet {0} but got {1}", packetNumber, buff[0]), false);
                                }

                                packetNumber = buff[0];
                                outputData   = true;
                            }
                            else if (buff[0] < packetNumber)
                            {
                                if (cmdParams.Verbose)
                                {
                                    Error(string.Format("Duplicated packet, expected packet {0} but got {1}", packetNumber, buff[0]), false);
                                }
                            }
                            else
                            {
                                outputData = true;
                            }
                        }
                        else
                        {
                            outputData = true;
                        }

                        if (outputData)
                        {
                            packetNumber++;
                            var offset = cmdParams.PacketNumbering ? 1 : 0;

                            if (!cmdParams.HexOutput)
                            {
                                stream.Write(buff, offset, read - offset);
                            }
                            else
                            {
                                // .TaArray() added due to Mono compatibility issues
                                var hexOutput = Encoding.ASCII.GetBytes(string.Join(" ", buff.Skip(offset).Select(b => b.ToString("X2")).ToArray()));
                                stream.Write(hexOutput, 0, hexOutput.Length);
                            }

                            if (cmdParams.NewLineAfterPacket)
                            {
                                stream.Write(newline, 0, newline.Length);
                            }

                            stream.Flush();
                        }
                    }
                }
            }
        }
Пример #23
0
        private static void Sending(MonoUsbDeviceHandle rapidradio, Params cmdParams)
        {
            StartReadingThread(rapidradio);

            try
            {
                using (var stream = Console.OpenStandardInput())
                {
                    byte packetNumber = 0;
                    var  buff         = new byte[32];
                    while (true)
                    {
                        int read = 0;
                        int b;
                        int offset = cmdParams.PacketNumbering ? 1 : 0;
                        do
                        {
                            b = stream.ReadByte();
                            if (b > -1)
                            {
                                buff[offset + read++] = (byte)b;
                            }
                        } while (read < 32 - offset && b != -1 && b != '\r' && b != '\n');

                        if (read > 0)
                        {
                            try
                            {
                                if (cmdParams.PacketNumbering)
                                {
                                    buff[0] = packetNumber++;
                                }

                                var buffCopy = new byte[32];
                                Array.Copy(buff, buffCopy, read + (cmdParams.PacketNumbering ? 1 : 0));
                                SendData(rapidradio, 2, buffCopy, read + (cmdParams.PacketNumbering ? 1 : 0));
                            }
                            catch (Exception e)
                            {
                                Error(e.Message, false);
                            }
                        }

                        if (b == -1)
                        {
                            break;
                        }
                    }
                }

                // send transmission end packet
                try
                {
                    SendData(rapidradio, 2, TransmissionEndToken, 32);
                }
                catch (Exception e)
                {
                    Error(e.Message, false);
                }
            }
            catch (Exception e)
            {
                Error(GetRecursiveMessage(e, 10));
            }

            StopReadingThread();
        }
Пример #24
0
        // This function originated from do_sync_bulk_transfer()
        // in sync.c of the Libusb-1.0 source code.
        private static MonoUsbError doBulkAsyncTransfer(MonoUsbDeviceHandle dev_handle,
                                                        byte endpoint,
                                                        byte[] buffer,
                                                        int length,
                                                        out int transferred,
                                                        int timeout)
        {
            transferred = 0;
            MonoUsbTransfer transfer = new MonoUsbTransfer(0);

            if (transfer.IsInvalid)
            {
                return(MonoUsbError.ErrorNoMem);
            }

            MonoUsbTransferDelegate monoUsbTransferCallbackDelegate = bulkTransferCB;

            int[]    userCompleted   = new int[] { 0 };
            GCHandle gcUserCompleted = GCHandle.Alloc(userCompleted, GCHandleType.Pinned);

            MonoUsbError e;
            GCHandle     gcBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned);

            transfer.FillBulk(
                dev_handle,
                endpoint,
                gcBuffer.AddrOfPinnedObject(),
                length,
                monoUsbTransferCallbackDelegate,
                gcUserCompleted.AddrOfPinnedObject(),
                timeout);

            e = transfer.Submit();
            if ((int)e < 0)
            {
                transfer.Free();
                gcUserCompleted.Free();
                return(e);
            }
            int r;

            Console.WriteLine("Transfer Submitted..");
            while (userCompleted[0] == 0)
            {
                e = (MonoUsbError)(r = Usb.HandleEvents(sessionHandle));
                if (r < 0)
                {
                    if (e == MonoUsbError.ErrorInterrupted)
                    {
                        continue;
                    }
                    transfer.Cancel();
                    while (userCompleted[0] == 0)
                    {
                        if (Usb.HandleEvents(sessionHandle) < 0)
                        {
                            break;
                        }
                    }
                    transfer.Free();
                    gcUserCompleted.Free();
                    return(e);
                }
            }

            transferred = transfer.ActualLength;
            e           = MonoUsbApi.MonoLibUsbErrorFromTransferStatus(transfer.Status);
            transfer.Free();
            gcUserCompleted.Free();
            return(e);
        }
Пример #25
0
 private void CleanUpHandle(MonoUsbDeviceHandle handle)
 {
     MonoUsbApi.ReleaseInterface(handle, 0);
     handle.Close();
     Disconnect(false);
 }
Пример #26
0
        public PSVR(bool EnableSensor)
        {
            if (CurrentOS.IsWindows)
            {
                var ndev = UsbDevice.AllDevices.Where(d => d.Vid == 0x54C && d.Pid == 0x09AF && d.SymbolicName.ToLower().Contains("mi_05")).FirstOrDefault();

                if (ndev == null)
                {
                    throw new InvalidOperationException("No Control device found");
                }

                if (!ndev.Open(out controlDevice))
                {
                    throw new InvalidOperationException("Device in use");
                }

                ndev = UsbDevice.AllDevices.Where(d => d.Vid == 0x54C && d.Pid == 0x09AF && d.SymbolicName.ToLower().Contains("mi_04")).FirstOrDefault();

                if (ndev == null)
                {
                    controlDevice.Close();
                    throw new InvalidOperationException("No Sensor device found");
                }

                if (EnableSensor)
                {
                    if (!ndev.Open(out sensorDevice))
                    {
                        controlDevice.Close();
                        throw new InvalidOperationException("Device in use");
                    }
                }

                writer    = controlDevice.OpenEndpointWriter(LibUsbDotNet.Main.WriteEndpointID.Ep04);
                cmdReader = controlDevice.OpenEndpointReader(LibUsbDotNet.Main.ReadEndpointID.Ep04);
                cmdReader.DataReceived       += CmdReader_DataReceived;
                cmdReader.DataReceivedEnabled = true;

                if (EnableSensor)
                {
                    reader = sensorDevice.OpenEndpointReader(LibUsbDotNet.Main.ReadEndpointID.Ep03, 64);
                    reader.DataReceived       += Reader_DataReceived;
                    reader.DataReceivedEnabled = true;
                }

                aliveTimer = new Timer(is_alive);
                aliveTimer.Change(2000, 2000);
            }
            else
            {
                var found = UsbDevice.AllDevices.Where(d => d.Vid == 0x54C && d.Pid == 0x09AF).FirstOrDefault();

                controlDevice = found.Device;

                var dev = (MonoUsbDevice)controlDevice;

                var handle = new MonoUsbDeviceHandle(dev.Profile.ProfileHandle);

                MonoUsbApi.DetachKernelDriver(handle, 5);

                if (EnableSensor)
                {
                    MonoUsbApi.DetachKernelDriver(handle, 4);
                }

                if (!dev.ClaimInterface(5))
                {
                    controlDevice.Close();
                    throw new InvalidOperationException("Device in use");
                }

                if (EnableSensor)
                {
                    if (!dev.ClaimInterface(4))
                    {
                        controlDevice.Close();
                        throw new InvalidOperationException("Device in use");
                    }
                }

                writer = dev.OpenEndpointWriter(LibUsbDotNet.Main.WriteEndpointID.Ep04);

                if (EnableSensor)
                {
                    reader = dev.OpenEndpointReader(LibUsbDotNet.Main.ReadEndpointID.Ep03, 64);
                    reader.DataReceived       += Reader_DataReceived;
                    reader.DataReceivedEnabled = true;
                }
            }
        }
Пример #27
0
        static void Main(string[] args)
        {
            MonoUsbSessionHandle sessionHandle = null;
            MonoUsbDeviceHandle  rapidradio    = null;

            try
            {
                if (args.Length == 1 && args[0] == "--help")
                {
                    Usage();
                    return;
                }

                var cmdParams = ParseCmdParams(args);

                // set up USB lib
                sessionHandle = new MonoUsbSessionHandle();
                if (sessionHandle.IsInvalid)
                {
                    throw new Exception("Invalid session handle.");
                }

                MonoUsbProfileListHandle list;
                MonoUsbApi.GetDeviceList(sessionHandle, out list);

                var profileList = new MonoUsbProfileList();
                profileList.Refresh(sessionHandle);
                var rapidradios = profileList.Where(d => d.DeviceDescriptor != null && d.DeviceDescriptor.VendorID == Vid && d.DeviceDescriptor.ProductID == Pid).ToArray();

                if (rapidradios.Length == 0)
                {
                    Error("rapidradio USB device not found");
                }

                if (rapidradios.Length > 1)
                {
                    // more than 1 rapidradio USB attached
                    Error(string.Format("Detected {0} rapidradio USB modules - currently only one device is supported.", rapidradios.Length), false);
                }

                rapidradio = rapidradios[0].OpenDeviceHandle();
                if (rapidradio == null || rapidradio.IsInvalid)
                {
                    throw new Exception("Invalid session handle.");
                }
                var r = MonoUsbApi.SetConfiguration(rapidradio, 1);
                if (r != 0)
                {
                    Error("SetConfiguration error: " + GetErrorMessage(r));
                }
                r = MonoUsbApi.ClaimInterface(rapidradio, 0);
                if (r != 0)
                {
                    Error("ClaimInterface error: " + GetErrorMessage(r));
                }

                _unmanagedReadBuff  = Marshal.AllocHGlobal(32);
                _unmanagedWriteBuff = Marshal.AllocHGlobal(32);

                // send configuration to endpoint 4
                var settings = cmdParams.Serialize();
                SendData(rapidradio, 4, settings, settings.Length, 200);

                // send custom register settings (if any)
                foreach (var regPacket in cmdParams.SerializeRfmRegisters())
                {
                    if (cmdParams.Verbose)
                    {
                        Info(string.Format("Setting register R{0}={1}", regPacket[1], regPacket[2]));
                    }

                    SendData(rapidradio, 4, regPacket, regPacket.Length);
                }

                var stopWatch = new Stopwatch();
                if (_stats)
                {
                    stopWatch.Start();
                }

                if (cmdParams.Verbose)
                {
                    Info(string.Format("Address = 0x{0}", cmdParams.Address.ToString("X8")));
                    Info(string.Format("Channel = {0}", cmdParams.Channel));
                    Info(string.Format("Mode = {0}", cmdParams.SinglePacket == null ? cmdParams.Mode.ToString() : "Single Packet Mode"));
                    Info(string.Format("ACK {0}", cmdParams.Ack ? "enabled" : "disabled"));
                    Info(string.Format("Retries = {0}", cmdParams.Retries));
                    if (cmdParams.SinglePacket == null)
                    {
                        Info(string.Format("Packet Numbering {0}", cmdParams.PacketNumbering ? "enabled" : "disabled"));
                    }
                }

                if (cmdParams.SinglePacket != null)
                {
                    // send exactly one packet
                    StartReadingThread(rapidradio);
                    SendData(rapidradio, 2, cmdParams.SinglePacket.ToArray(), cmdParams.SinglePacket.Count);
                    StopReadingThread();
                }
                else
                {
                    switch (cmdParams.Mode)
                    {
                    case RadioMode.Listening:
                        Listening(rapidradio, cmdParams);
                        break;

                    case RadioMode.Sending:
                        Sending(rapidradio, cmdParams);
                        break;

                    default:
                        throw new ArgumentOutOfRangeException("Unknown mode");
                    }
                }

                if (_stats)
                {
                    Info("Transmission took " + stopWatch.Elapsed);
                }

                // switch off the radio
                TurnOff(rapidradio);
            }
            catch (Exception e)
            {
                Error("An error occured: " + GetRecursiveMessage(e, 10));
            }
            finally
            {
                {
                    // Free and close resources
                    if (rapidradio != null)
                    {
                        if (!rapidradio.IsInvalid)
                        {
                            MonoUsbApi.ReleaseInterface(rapidradio, 0);
                            rapidradio.Close();
                        }
                    }

                    if (sessionHandle != null)
                    {
                        sessionHandle.Close();
                    }

                    Marshal.FreeHGlobal(_unmanagedReadBuff);
                    Marshal.FreeHGlobal(_unmanagedWriteBuff);
                }
            }
        }
        public static void ShowConfig(RichTextBox rtb)
        {
            // Assign the control transfer delegate to the callback function.
            controlTransferDelegate = ControlTransferCB;

            // Initialize the context.
            sessionHandle = new MonoUsbSessionHandle();
            if (sessionHandle.IsInvalid)
            {
                throw new Exception(String.Format("Failed intializing libusb context.\n{0}:{1}",
                                                  MonoUsbSessionHandle.LastErrorCode,
                                                  MonoUsbSessionHandle.LastErrorString));
            }

            MonoUsbProfileList  profileList    = new MonoUsbProfileList();
            MonoUsbDeviceHandle myDeviceHandle = null;

            try
            {
                // The list is initially empty.
                // Each time refresh is called the list contents are updated.
                profileList.Refresh(sessionHandle);

                // Use the GetList() method to get a generic List of MonoUsbProfiles
                // Find the first profile that matches in MyVidPidPredicate.
                MonoUsbProfile myProfile = profileList.GetList().Find(MyVidPidPredicate);
                if (myProfile == null)
                {
                    rtb.AppendText("Device not connected.");
                    return;
                }

                // Open the device handle to perform I/O
                myDeviceHandle = myProfile.OpenDeviceHandle();
                if (myDeviceHandle.IsInvalid)
                {
                    throw new Exception(String.Format("Failed opening device handle.\n{0}:{1}",
                                                      MonoUsbDeviceHandle.LastErrorCode,
                                                      MonoUsbDeviceHandle.LastErrorString));
                }
                int          ret;
                MonoUsbError e;

                // Set Configuration
                e = (MonoUsbError)(ret = MonoUsbApi.SetConfiguration(myDeviceHandle, 1));
                if (ret < 0)
                {
                    throw new Exception(String.Format("Failed SetConfiguration.\n{0}:{1}", e, MonoUsbApi.StrError(e)));
                }

                // Claim Interface
                e = (MonoUsbError)(ret = MonoUsbApi.ClaimInterface(myDeviceHandle, 0));
                if (ret < 0)
                {
                    throw new Exception(String.Format("Failed ClaimInterface.\n{0}:{1}", e, MonoUsbApi.StrError(e)));
                }

                // Create a vendor specific control setup, allocate 1 byte for return control data.
                byte requestType = (byte)(UsbCtrlFlags.Direction_In | UsbCtrlFlags.Recipient_Device | UsbCtrlFlags.RequestType_Vendor);
                byte request     = 0x0F;
                MonoUsbControlSetupHandle controlSetupHandle = new MonoUsbControlSetupHandle(requestType, request, 0, 0, 1);

                // Transfer the control setup packet
                ret = libusb_control_transfer(myDeviceHandle, controlSetupHandle, 1000);
                if (ret > 0)
                {
                    rtb.AppendText("\nSuccess!\n");
                    byte[] ctrlDataBytes  = controlSetupHandle.ControlSetup.GetData(ret);
                    string ctrlDataString = Helper.HexString(ctrlDataBytes, String.Empty, "h ");
                    rtb.AppendText(string.Format("Return Length: {0}", ret));
                    rtb.AppendText(string.Format("DATA (hex)   : [ {0} ]\n", ctrlDataString.Trim()));
                }
                MonoUsbApi.ReleaseInterface(myDeviceHandle, 0);
            }
            finally
            {
                profileList.Close();
                if (myDeviceHandle != null)
                {
                    myDeviceHandle.Close();
                }
                sessionHandle.Close();
            }
        }
 /// <summary>
 /// Perform a USB control transfer.
 /// </summary>
 /// <remarks>
 /// The direction of the transfer is inferred from the bmRequestType field of the setup packet. 
 /// The wValue, wIndex and wLength fields values should be given in host-endian byte order.
 /// </remarks>
 /// <param name="deviceHandle">A handle for the device to communicate with.</param>
 /// <param name="setupPacket">The setup packet.</param>
 /// <param name="pData">A suitably-sized data buffer for either input or output (depending on direction bits within bmRequestType).</param>
 /// <param name="dataLength">The length field for the setup packet. The data buffer should be at least this size.</param>
 /// <param name="timeout">timeout (in millseconds) that this function should wait before giving up due to no response being received. For an unlimited timeout, use value 0.</param>
 /// <returns>on success, the number of bytes actually transferred, Other wise a <see cref="MonoUsbError"/>.</returns>
     public static int libusb_control_transfer(MonoUsbDeviceHandle deviceHandle,
                                               ref libusb_control_setup setupPacket,
                                               IntPtr pData,
                                               short dataLength,
                                               int timeout)
     {
         return libusb_control_transfer(deviceHandle,
                                        setupPacket.bmRequestType,
                                        setupPacket.bRequest,
                                        setupPacket.wValue,
                                        setupPacket.wIndex,
                                        pData,
                                        dataLength,
                                        timeout);
     }