Exemple #1
0
        // there is no connect, we just check if we can open and claim an interface, and if we can then we can "connect"
        public bool Connect()
        {
            lock (_sync)
            {
                if (context != null)
                {
                    if (!context.IsClosed)
                    {
                        context.Close();
                    }
                    context.Dispose();
                    context = null;
                }

                context = new MonoUsbSessionHandle();
                var usbHandle = MonoUsbApi.OpenDeviceWithVidPid(context, 1406, 12288);
                if (usbHandle != null)
                {
                    if (MonoUsbApi.ClaimInterface(usbHandle, 0) == 0)
                    {
                        MonoUsbApi.ReleaseInterface(usbHandle, 0);
                        usbHandle.Close();
                        Connected = true;
                        return(true);
                    }
                    usbHandle.Close();
                }
                else
                {
                    throw new Exception("Console not found or usb driver failed to open device. Is the console connected and is libusb configured correctly?");
                }

                Connected = false;
                UnityEngine.Debug.Log("Failed");
                return(false);
            }
        }
Exemple #2
0
        public void Close()
        {
            profileList.Close();
            if (myDeviceHandle != null)
            {
                myDeviceHandle.Close();
            }
            sessionHandle.Close();

            if (MyUsbDevice != null)
            {
                if (MyUsbDevice.IsOpen)
                {
                    IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                    if (!ReferenceEquals(wholeUsbDevice, null))
                    {
                        wholeUsbDevice.ReleaseInterface(0);
                    }
                    MyUsbDevice.Close();
                }

                MyUsbDevice = null;
            }
        }
Exemple #3
0
 public void Exit()
 {
     usbSession.Close();
 }
        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();
            }
        }
Exemple #5
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);
        }
        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;
        }
Exemple #7
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();
        }
Exemple #8
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);
                }
            }
        }
Exemple #9
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");
            }
        }
 public void Dispose()
 {
     usbSession.Close();
 }