Ejemplo n.º 1
0
        public static void Main(string[] args)
        {
            int ret;
            MonoUsbProfileList profileList = null;

            // Initialize the context.
            if (Session.IsInvalid)
                throw new Exception("Failed to initialize context.");

            MonoUsbApi.SetDebug(Session, 0);
            // Create a MonoUsbProfileList instance.
            profileList = new MonoUsbProfileList();

            // The list is initially empty.
            // Each time refresh is called the list contents are updated.
            ret = profileList.Refresh(Session);
            if (ret < 0) throw new Exception("Failed to retrieve device list.");
            Console.WriteLine("{0} device(s) found.", ret);

            // Iterate through the profile list; write the device descriptor to
            // console output.
            foreach (MonoUsbProfile profile in profileList)
                Console.WriteLine(profile.DeviceDescriptor);

            // Since profile list, profiles, and sessions use safe handles the
            // code below is not required but it is considered good programming
            // to explicitly free and close these handle when they are no longer
            // in-use.
            profileList.Close();
            Session.Close();
        }
Ejemplo n.º 2
0
        public static void SwitchAllFound()
        {
            MonoUsbSessionHandle session = new MonoUsbSessionHandle();

            if (session.IsInvalid)
            {
                throw new Exception("The USB session handle was invalid.");
            }

            MonoUsbProfileList list = new MonoUsbProfileList();

            if (list.Refresh(session) < 0)
            {
                throw new Exception("USB refresh profile list from session failed.");
            }

            // 0x4255:0x0001 (Config Mode)
            // 0x4255:0x1000 (Mass Storage Mode)

            foreach (MonoUsbProfile profile in list)
            {
                short vendor_id  = profile.DeviceDescriptor.VendorID;
                short product_id = profile.DeviceDescriptor.ProductID;

                if (vendor_id == 0x4255 && product_id == 0x0001)
                {
                    // BodyCam Configuration Mode
                    HandleConfigModeDevice(profile);
                }

                profile.Close();
            }
        }
Ejemplo n.º 3
0
 internal static int RefreshProfileList()
 {
     lock (OLockDeviceList)
     {
         MonoUsbApi.InitAndStart();
         if (mMonoUSBProfileList == null)
         {
             mMonoUSBProfileList = new MonoUsbProfileList();
         }
         return((int)mMonoUSBProfileList.Refresh(MonoUsbEventHandler.SessionHandle));
     }
 }
Ejemplo n.º 4
0
        public MonoDeviceServer()
        {
            int numDevices = -1;

            // Initialize the context.
            if (Session.IsInvalid)
            {
                throw new Exception("Failed to initialize context.");
            }

            MonoUsbApi.SetDebug(Session, 0);
            // Create a MonoUsbProfileList instance.
            profileList = new MonoUsbProfileList();

            cts = new CancellationTokenSource();
            var ct = cts.Token;

            Task.Run(async() =>
            {
                try
                {
                    while (!ct.IsCancellationRequested)
                    {
                        // The list is initially empty.
                        // Each time refresh is called the list contents are updated.
                        int ret = profileList.Refresh(Session);
                        if (ret < 0)
                        {
                            throw new Exception("Failed to retrieve device list.");
                        }

                        if (numDevices != ret)
                        {
                            numDevices = ret;
                            //Console.WriteLine($"{numDevices} device(s) found.");
                            MonoSetDevice();
                        }

                        await Task.Delay(1000, ct);
                    }
                }
                finally
                {
                    // Since profile list, profiles, and sessions use safe handles the
                    // code below is not required but it is considered good programming
                    // to explicitly free and close these handle when they are no longer
                    // in-use.
                    profileList.Close();
                    Session.Close();
                }
            }, ct);
        }
Ejemplo n.º 5
0
        public static void ShowInfo(RichTextBox rtb)
        {
            int ret;
            MonoUsbProfileList profileList = null;

            // Initialize the context.
            if (Session.IsInvalid)
            {
                throw new Exception("Failed to initialize context.");
            }

            MonoUsbApi.SetDebug(Session, 0);
            // Create a MonoUsbProfileList instance.
            profileList = new MonoUsbProfileList();

            // The list is initially empty.
            // Each time refresh is called the list contents are updated.
            ret = profileList.Refresh(Session);
            if (ret < 0)
            {
                throw new Exception("Failed to retrieve device list.");
            }

            rtb.AppendText(string.Format("{0} device(s) found.\r\n", ret));

            MonoUsbProfile JagaProfile;

            // Iterate through the profile list; write the device descriptor to
            // console output.
            foreach (MonoUsbProfile profile in profileList)
            {
                rtb.AppendText(profile.DeviceDescriptor.ToString() + "\r\n");

                if (profile.DeviceDescriptor.VendorID == 0x1915)
                {
                    JagaProfile = profile;
                }
            }



            // Since profile list, profiles, and sessions use safe handles the
            // code below is not required but it is considered good programming
            // to explicitly free and close these handle when they are no longer
            // in-use.
            profileList.Close();
            Session.Close();
        }
Ejemplo n.º 6
0
        public static void Main(string[] args)
        {
            int ret;
            MonoUsbProfileList profileList = null;

            // Initialize the context.
            if (Session.IsInvalid)
            {
                throw new Exception("Failed to initialize context.");
            }

            MonoUsbApi.SetDebug(Session, 0);
            // Create a MonoUsbProfileList instance.
            profileList = new MonoUsbProfileList();

            // The list is initially empty.
            // Each time refresh is called the list contents are updated.
            ret = profileList.Refresh(Session);
            if (ret < 0)
            {
                throw new Exception("Failed to retrieve device list.");
            }
            Console.WriteLine("{0} device(s) found.", ret);

            // Iterate through the profile list; write the device descriptor to
            // console output.
            foreach (MonoUsbProfile profile in profileList)
            {
                Console.WriteLine(profile.DeviceDescriptor);
            }

            // Since profile list, profiles, and sessions use safe handles the
            // code below is not required but it is considered good programming
            // to explicitly free and close these handle when they are no longer
            // in-use.
            profileList.Close();
            Session.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();
            }
        }
Ejemplo n.º 8
0
        private static void Main(string[] args)
        {
            // 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)
                {
                    Console.WriteLine("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)
                {
                    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();
            }
        }
Ejemplo n.º 9
0
        public static void Main(string[] args)
        {
            // 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.");
            Console.WriteLine("{0} device(s) found.", 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)
            {
                // Write the VendorID and ProductID to console output.
                Console.WriteLine("[Device] Vid:{0:X4} Pid:{1:X4}", 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.
                    Console.WriteLine("  [Config] bConfigurationValue:{0}", 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.
                            Console.WriteLine("    [Interface] bInterfaceNumber:{0} bAlternateSetting:{1}",
                                              usbAltInterface.bInterfaceNumber,
                                              usbAltInterface.bAlternateSetting);

                            // Interate through the EndpointList
                            foreach (MonoUsbEndpointDescriptor endpoint in usbAltInterface.EndpointList)
                            {
                                // Write the bEndpointAddress, EndpointType, and wMaxPacketSize to console output.
                                Console.WriteLine("      [Endpoint] bEndpointAddress:{0:X2} EndpointType:{1} wMaxPacketSize:{2}",
                                                  endpoint.bEndpointAddress,
                                                  (EndpointType) (endpoint.bmAttributes & 0x3),
                                                  endpoint.wMaxPacketSize);
                            }
                        }
                    }
                    // Not neccessary, but good programming practice.
                    configHandle.Close();
                }
            }
            // Not neccessary, but good programming practice.
            profileList.Close();
            // Not neccessary, but good programming practice.
            sessionHandle.Close();
        }
Ejemplo n.º 10
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();
        }
Ejemplo n.º 11
0
        void findWasatchProfiles()
        {
            if (monoUsbSession == null || monoUsbSession.IsInvalid)
            {
                return;
            }

            MonoUsbProfileList profileList = new MonoUsbProfileList();

            int deviceCount = profileList.Refresh(monoUsbSession);

            if (deviceCount < 0)
            {
                logger.error("init: Failed to retrieve device list");
                return;
            }
            logger.info("{0} device(s) found.", deviceCount);

            profiles = profileList.GetList().FindAll(predicateWasatchVid);
            foreach (MonoUsbProfile profile in profiles)
            {
                logger.info("[Device] Vid:{0:X4} Pid:{1:X4}", profile.DeviceDescriptor.VendorID, profile.DeviceDescriptor.ProductID);
                logger.info("  Descriptors: {0}", profile.DeviceDescriptor);

                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("  [Config] bConfigurationValue: {0}", configDescriptor.bConfigurationValue);

                    foreach (MonoUsbInterface usbInterface in configDescriptor.InterfaceList)
                    {
                        foreach (MonoUsbAltInterfaceDescriptor usbAltInterface in usbInterface.AltInterfaceList)
                        {
                            logger.info("    [Interface] bInterfaceNumber: {0}, bAlternateSetting: {1}",
                                        usbAltInterface.bInterfaceNumber, usbAltInterface.bAlternateSetting);

                            foreach (MonoUsbEndpointDescriptor endpoint in usbAltInterface.EndpointList)
                            {
                                // Write the bEndpointAddress, EndpointType, and wMaxPacketSize to console output.
                                logger.info("      [Endpoint] bEndpointAddress: 0x{0:X2}, EndpointType: {1}, wMaxPacketSize: {2}",
                                            endpoint.bEndpointAddress, (EndpointType)(endpoint.bmAttributes & 0x3), endpoint.wMaxPacketSize);
                            }
                        }
                    }
                    configHandle.Close();
                }
                // profile.Close();
            }
        }
Ejemplo n.º 12
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);
                }
            }
        }
Ejemplo n.º 13
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");
            }
        }
Ejemplo n.º 14
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);
        }