Exemple #1
0
        public void Sync()
        {
            Guid          HIDServiceClass = Guid.Parse(NativeImports.HID_GUID);
            List <IntPtr> btRadios        = new List <IntPtr>();
            int           pairedCount     = 0;
            IntPtr        foundRadio;
            IntPtr        handle;

            NativeImports.BLUETOOTH_FIND_RADIO_PARAMS radioParams = new NativeImports.BLUETOOTH_FIND_RADIO_PARAMS();

            radioParams.Initialize();

            handle = NativeImports.BluetoothFindFirstRadio(ref radioParams, out foundRadio);
            bool next = handle != IntPtr.Zero;

            do
            {
                if (foundRadio != IntPtr.Zero)
                {
                    btRadios.Add(foundRadio);
                }

                next = NativeImports.BluetoothFindNextRadio(ref handle, out foundRadio);
            }while (next);

            if (btRadios.Count > 0)
            {
                Prompt(Globalization.Translate("Sync_Searching"));

                while (pairedCount == 0 && !cancelled)
                {
                    for (int r = 0; r < btRadios.Count; r++)
                    {
                        IntPtr found;
                        NativeImports.BLUETOOTH_RADIO_INFO           radioInfo    = new NativeImports.BLUETOOTH_RADIO_INFO();
                        NativeImports.BLUETOOTH_DEVICE_INFO          deviceInfo   = new NativeImports.BLUETOOTH_DEVICE_INFO();
                        NativeImports.BLUETOOTH_DEVICE_SEARCH_PARAMS searchParams = new NativeImports.BLUETOOTH_DEVICE_SEARCH_PARAMS();

                        radioInfo.Initialize();
                        deviceInfo.Initialize();
                        searchParams.Initialize();

                        uint getInfoError = NativeImports.BluetoothGetRadioInfo(btRadios[r], ref radioInfo);

                        // Success
                        if (getInfoError == 0)
                        {
                            searchParams.fReturnAuthenticated = false;
                            searchParams.fReturnRemembered    = false;
                            searchParams.fReturnConnected     = false;
                            searchParams.fReturnUnknown       = true;
                            searchParams.fIssueInquiry        = true;
                            searchParams.cTimeoutMultiplier   = 2;
                            searchParams.hRadio = btRadios[r];

                            found = NativeImports.BluetoothFindFirstDevice(ref searchParams, ref deviceInfo);

                            if (found != IntPtr.Zero)
                            {
                                do
                                {
                                    bool controller = SupportedDevice(deviceInfo.szName);
                                    bool wiiDevice  = deviceInfo.szName.StartsWith("Nintendo RVL");

                                    if (controller || wiiDevice)
                                    {
                                        Prompt(Globalization.TranslateFormat("Sync_Found", deviceInfo.szName));

                                        StringBuilder password  = new StringBuilder();
                                        uint          pcService = 16;
                                        Guid[]        guids     = new Guid[16];
                                        bool          success   = true;

                                        if (deviceInfo.fRemembered)
                                        {
                                            // Remove current pairing
                                            Prompt(Globalization.TranslateFormat("Sync_Unpairing"));
                                            uint errForget = NativeImports.BluetoothRemoveDevice(ref deviceInfo.Address);
                                            success = errForget == 0;
                                        }

                                        if (wiiDevice)
                                        {
                                            // use MAC address of BT radio as pin
                                            var bytes = BitConverter.GetBytes(radioInfo.address);
                                            for (int i = 0; i < 6; i++)
                                            {
                                                password.Append((char)bytes[i]);
                                            }

                                            if (success)
                                            {
                                                Prompt(Globalization.Translate("Sync_Pairing"));
                                                var errPair = NativeImports.BluetoothAuthenticateDevice(IntPtr.Zero, btRadios[r], ref deviceInfo, password.ToString(), 6);
                                                success = errPair == 0;
                                            }

                                            if (success)
                                            {
                                                Prompt(Globalization.Translate("Sync_Service"));
                                                var errService = NativeImports.BluetoothEnumerateInstalledServices(btRadios[r], ref deviceInfo, ref pcService, guids);
                                                success = errService == 0;
                                            }

                                            if (success)
                                            {
                                                Prompt(Globalization.Translate("Sync_HID"));
                                                var errActivate = NativeImports.BluetoothSetServiceState(btRadios[r], ref deviceInfo, ref HIDServiceClass, 0x01);
                                                success = errActivate == 0;
                                            }

                                            if (success)
                                            {
                                                Prompt(Globalization.Translate("Sync_Success"));
                                                pairedCount += 1;
                                            }
                                            else
                                            {
                                                Prompt(Globalization.Translate("Sync_Failure"));
                                            }
                                        }
                                        else
                                        {
                                            Prompt(Globalization.Translate("Sync_Finish"));
                                            var err = NativeImports.BluetoothAuthenticateDeviceEx(IntPtr.Zero, btRadios[r], ref deviceInfo, null, NativeImports.AUTHENTICATION_REQUIREMENTS.MITMProtectionNotRequired);

                                            if (err == 0)
                                            {
                                                Prompt(Globalization.Translate("Sync_Success"));
                                                pairedCount += 1;
                                            }
                                            else
                                            {
                                                Prompt(Globalization.Translate("Sync_Incomplete"));
                                            }
                                        }
                                    }
                                }while (NativeImports.BluetoothFindNextDevice(found, ref deviceInfo));
                            }
                        }
                        else
                        {
                            // Failed to get Bluetooth Radio Info
                            Prompt(Globalization.Translate("Sync_Bluetooth_Failed"));
                        }
                    }
                }

                // Close Opened Radios
                foreach (var openRadio in btRadios)
                {
                    NativeImports.CloseHandle(openRadio);
                }
            }
            else
            {
                // No Bluetooth Radios found
                Prompt(Globalization.Translate("Sync_No_Bluetooth"));
                System.Threading.Thread.Sleep(3000);
            }

            NativeImports.BluetoothFindRadioClose(handle);

            Dispatcher.BeginInvoke((Action)(() => Close()));
        }
        public void Sync()
        {
            WiitarDebug.Log("FUNC BEGIN - Sync");

            WiitarDebug.Log("BEF - BLUETOOTH_FIND_RADIO_PARAMS");
            var radioParams = new NativeImports.BLUETOOTH_FIND_RADIO_PARAMS();

            WiitarDebug.Log("AFT - BLUETOOTH_FIND_RADIO_PARAMS");
            Guid          HidServiceClass = Guid.Parse(NativeImports.HID_GUID);
            List <IntPtr> btRadios        = new List <IntPtr>();
            IntPtr        foundRadio;
            IntPtr        foundResult;

            radioParams.Initialize();

            // Get first BT Radio
            WiitarDebug.Log("BEF - BluetoothGetRadioInfo");
            foundResult = NativeImports.BluetoothFindFirstRadio(ref radioParams, out foundRadio);
            WiitarDebug.Log("AFT - BluetoothGetRadioInfo");
            bool more = foundResult != IntPtr.Zero;

            do
            {
                if (foundRadio != IntPtr.Zero)
                {
                    btRadios.Add(foundRadio);
                }

                // Find more
                WiitarDebug.Log("BEF - BluetoothFindNextRadio");
                more = NativeImports.BluetoothFindNextRadio(ref radioParams, out foundRadio);
                WiitarDebug.Log("AFT - BluetoothFindNextRadio");
            } while (more);

            if (btRadios.Count > 0)
            {
                Prompt("Searching for controllers...", isBold: true);

                // Search until cancelled or at least one device is paired
                while (!Cancelled && Count == 0)
                {
                    foreach (var radio in btRadios)
                    {
                        IntPtr found;

                        WiitarDebug.Log("BEF - BLUETOOTH_RADIO_INFO");
                        var radioInfo = new NativeImports.BLUETOOTH_RADIO_INFO();
                        WiitarDebug.Log("AFT - BLUETOOTH_RADIO_INFO");

                        WiitarDebug.Log("BEF - BLUETOOTH_DEVICE_INFO");
                        var deviceInfo = new NativeImports.BLUETOOTH_DEVICE_INFO();
                        WiitarDebug.Log("AFT - BLUETOOTH_DEVICE_INFO");

                        WiitarDebug.Log("BEF - BLUETOOTH_DEVICE_SEARCH_PARAMS");
                        var searchParams = new NativeImports.BLUETOOTH_DEVICE_SEARCH_PARAMS();
                        WiitarDebug.Log("AFT - BLUETOOTH_DEVICE_SEARCH_PARAMS");

                        radioInfo.Initialize();
                        deviceInfo.Initialize();
                        searchParams.Initialize();

                        // Access radio information
                        WiitarDebug.Log("BEF - BluetoothGetRadioInfo");
                        uint getInfoError = NativeImports.BluetoothGetRadioInfo(radio, ref radioInfo);
                        WiitarDebug.Log("AFT - BluetoothGetRadioInfo");

                        // Success
                        if (getInfoError == 0)
                        {
                            // Set search parameters
                            searchParams.hRadio               = radio;
                            searchParams.fIssueInquiry        = true;
                            searchParams.fReturnUnknown       = true;
                            searchParams.fReturnConnected     = false;
                            searchParams.fReturnRemembered    = true;
                            searchParams.fReturnAuthenticated = false;
                            searchParams.cTimeoutMultiplier   = 2;

                            // Search for a device
                            WiitarDebug.Log("BEF - BluetoothFindFirstDevice");
                            found = NativeImports.BluetoothFindFirstDevice(ref searchParams, ref deviceInfo);
                            WiitarDebug.Log("AFT - BluetoothFindFirstDevice");

                            // Success
                            if (found != IntPtr.Zero)
                            {
                                do
                                {
                                    // Note: Switch Pro Controller is simply called "Pro Controller"
                                    if (deviceInfo.szName.StartsWith("Nintendo RVL-CNT-01"))
                                    {
//#if DEBUG
//                                        var str_fRemembered = deviceInfo.fRemembered ? ", but it is already synced!" : "";
//#else
//                                        if (deviceInfo.fRemembered)
//                                        {
//                                            continue;
//                                        }
//                                        var str_fRemembered = "";
//#endif

                                        var str_fRemembered = deviceInfo.fRemembered ? ", but it is already synced!" : ". Attempting to pair now...";

                                        if (deviceInfo.szName.Equals("Nintendo RVL-CNT-01"))
                                        {
                                            Prompt("Found Wiimote (\"" + deviceInfo.szName + "\")" + str_fRemembered, isBold: !deviceInfo.fRemembered, isItalic: deviceInfo.fRemembered, isSmall: deviceInfo.fRemembered);
                                        }
                                        else if (deviceInfo.szName.Equals("Nintendo RVL-CNT-01-TR"))
                                        {
                                            Prompt("Found 2nd-Gen Wiimote+ (\"" + deviceInfo.szName + "\")" + str_fRemembered, isBold: !deviceInfo.fRemembered, isItalic: deviceInfo.fRemembered, isSmall: deviceInfo.fRemembered);
                                        }
                                        else if (deviceInfo.szName.Equals("Nintendo RVL-CNT-01-UC"))
                                        {
                                            Prompt("Found Wii U Pro Controller (\"" + deviceInfo.szName + "\")" + str_fRemembered, isBold: !deviceInfo.fRemembered, isItalic: deviceInfo.fRemembered, isSmall: deviceInfo.fRemembered);
                                        }
                                        else
                                        {
                                            Prompt("Found Unknown Wii Device Type (\"" + deviceInfo.szName + "\")" + str_fRemembered, isBold: !deviceInfo.fRemembered, isItalic: deviceInfo.fRemembered, isSmall: deviceInfo.fRemembered);
                                        }

                                        if (deviceInfo.fRemembered)
                                        {
                                            continue;
                                        }


                                        StringBuilder password  = new StringBuilder();
                                        uint          pcService = 16;
                                        Guid[]        guids     = new Guid[16];
                                        bool          success   = true;

                                        var bytes = BitConverter.GetBytes(radioInfo.address);

                                        //// Create Password out of BT radio MAC address
                                        //if (BitConverter.IsLittleEndian)
                                        //{
                                        //    for (int i = 0; i < 6; i++)
                                        //    {
                                        //        password.Append((char)bytes[i]);
                                        //    }
                                        //}
                                        //else
                                        //{
                                        //    for (int i = 7; i >= 2; i--)
                                        //    {
                                        //        password.Append((char)bytes[i]);
                                        //    }
                                        //}

                                        for (int i = 0; i < 6; i++)
                                        {
                                            if (bytes[i] > 0)
                                            {
                                                password.Append((char)bytes[i]);
                                            }
                                        }

                                        uint errForget   = 0;
                                        uint errAuth     = 0;
                                        uint errService  = 0;
                                        uint errActivate = 0;


                                        //if (/*!ConnectedDeviceAddresses.Contains(deviceInfo.Address) && */(deviceInfo.fRemembered || deviceInfo.fConnected))
                                        //{
                                        //    // Remove current pairing
                                        //    Prompt("Device already in Bluetooth devices list. Removing from list before trying to sync...");
                                        //    errForget = NativeImports.BluetoothRemoveDevice(ref deviceInfo.Address);
                                        //    success = errForget == 0;

                                        //    if (success)
                                        //    {
                                        //        OnNewDeviceFound();
                                        //    }
                                        //}

                                        // Authenticate
                                        if (success)
                                        {
                                            WiitarDebug.Log("BEF - BluetoothAuthenticateDevice [SYNC]");
                                            errAuth = NativeImports.BluetoothAuthenticateDevice(IntPtr.Zero, radio, ref deviceInfo, password.ToString(), 6);
                                            WiitarDebug.Log("AFT - BluetoothAuthenticateDevice [SYNC]");
                                            //errAuth = NativeImports.BluetoothAuthenticateDeviceEx(IntPtr.Zero, radio, ref deviceInfo, null, NativeImports.AUTHENTICATION_REQUIREMENTS.MITMProtectionNotRequired);
                                            success = errAuth == 0;
                                        }

                                        //If it fails using SYNC method, try 1+2 method.
                                        if (!success)
                                        {
#if DEBUG
                                            Prompt("SYNC method didn't work. Trying 1+2 method...");
#endif

                                            var wiimoteBytes = BitConverter.GetBytes(deviceInfo.Address);

                                            password.Clear();

                                            for (int i = 0; i < 6; i++)
                                            {
                                                if (wiimoteBytes[i] > 0)
                                                {
                                                    password.Append((char)wiimoteBytes[i]);
                                                }
                                            }

                                            WiitarDebug.Log("BEF - BluetoothAuthenticateDevice [1+2]");
                                            errAuth = NativeImports.BluetoothAuthenticateDevice(IntPtr.Zero, radio, ref deviceInfo, password.ToString(), 6);
                                            WiitarDebug.Log("AFT - BluetoothAuthenticateDevice [1+2]");

                                            //errAuth = NativeImports.BluetoothAuthenticateDeviceEx(IntPtr.Zero, radio, ref deviceInfo, null, NativeImports.AUTHENTICATION_REQUIREMENTS.MITMProtectionNotRequired);
                                            success = errAuth == 0;
                                        }

                                        // Install PC Service
                                        if (success)
                                        {
                                            WiitarDebug.Log("BEF - BluetoothEnumerateInstalledServices");
                                            errService = NativeImports.BluetoothEnumerateInstalledServices(radio, ref deviceInfo, ref pcService, guids);
                                            WiitarDebug.Log("AFT - BluetoothEnumerateInstalledServices");
                                            success = errService == 0;
                                        }

                                        // Set to HID service
                                        if (success)
                                        {
                                            WiitarDebug.Log("BEF - BluetoothSetServiceState");
                                            errActivate = NativeImports.BluetoothSetServiceState(radio, ref deviceInfo, ref HidServiceClass, 0x01);
                                            WiitarDebug.Log("AFT - BluetoothSetServiceState");
                                            success = errActivate == 0;
                                        }

                                        if (success)
                                        {
                                            Prompt("Successfully Paired!", isBold: true);
                                            Count += 1;
                                        }
                                        else
                                        {
                                            var sb = new StringBuilder();
                                            //sb.AppendLine("Failed to pair.");

#if DEBUG
                                            sb.AppendLine("radio mac address: " + GetMacAddressStr(radioInfo.address));
                                            sb.AppendLine("wiimote mac address: " + GetMacAddressStr(deviceInfo.Address));
                                            sb.AppendLine("wiimote password: \"" + password.ToString() + "\"");
#endif


                                            if (errForget != 0)
                                            {
                                                sb.AppendLine(" >>> FAILED TO REMOVE DEVICE FROM BLUETOOTH DEVICES LIST. ERROR CODE 0x" + errForget.ToString("X"));
                                            }

                                            if (errAuth != 0)
                                            {
                                                sb.AppendLine(GetBluetoothAuthenticationError(errAuth));
                                            }

                                            if (errService != 0)
                                            {
                                                sb.AppendLine(" >>> SERVICE ERROR: " + new Win32Exception((int)errService).Message);
                                            }

                                            if (errActivate != 0)
                                            {
                                                sb.AppendLine(" >>> ACTIVATION ERROR: " + new Win32Exception((int)errActivate).Message);
                                            }

                                            Prompt(sb.ToString(), isBold: true, isItalic: true);
                                        }
                                    }
#if DEBUG
                                    else
                                    {
                                        Prompt("(Found \"" + deviceInfo.szName + "\", but it is not a Wiimote)", isBold: false, isItalic: false, isSmall: true, isDebug: true);
                                    }
#endif

                                    WiitarDebug.Log("About to try BluetoothFindNextDevice...");
                                } while (NativeImports.BluetoothFindNextDevice(found, ref deviceInfo));
                            }
                        }
                        else
                        {
                            // Failed to get BT Radio info
                            Prompt("Found Bluetooth adapter but was unable to interact with it.");
                        }
                    }
                }

                // Close each Radio
                foreach (var openRadio in btRadios)
                {
                    WiitarDebug.Log("BEF - CloseHandle");
                    NativeImports.CloseHandle(openRadio);
                    WiitarDebug.Log("AFT - CloseHandle");
                }
            }
            else
            {
                // No (compatable) Bluetooth
                Prompt(
                    "No compatble Bluetooth Radios found (IF YOU SEE THIS MESSAGE, MENTION IT WHEN ASKING FOR HELP!).", isBold: true, isItalic: true);
                _notCompatable = true;
                return;
            }

            // Close this window
            Dispatcher.BeginInvoke((Action)(() => Close()));

            WiitarDebug.Log("FUNC END - Sync");
        }
        public void Sync()
        {
            var radioParams = new NativeImports.BLUETOOTH_FIND_RADIO_PARAMS();

            radioParams.Initialize();
            Guid   HidServiceClass = Guid.Parse(NativeImports.HID_GUID);
            IntPtr hRadio;                                                                      //handle of bluetooth radio,                            close with CloseHandle()
            IntPtr hFind;                                                                       //handle needed to pass into BluetoothFindNextRadio,    close with BluetoothFindRadioClose()


            // Get first BT Radio and execute commands
            hFind = NativeImports.BluetoothFindFirstRadio(ref radioParams, out hRadio);
            if (hRadio != IntPtr.Zero)
            {
                //commands to execute per BT Radio
                do
                {
                    Prompt("Searching for controllers...");

                    // Search until cancelled or at least one device is paired
                    while (Count == 0 && !Cancelled)
                    {
                        IntPtr found;
                        var    radioInfo    = new NativeImports.BLUETOOTH_RADIO_INFO();
                        var    deviceInfo   = new NativeImports.BLUETOOTH_DEVICE_INFO();
                        var    searchParams = new NativeImports.BLUETOOTH_DEVICE_SEARCH_PARAMS();

                        radioInfo.Initialize();
                        deviceInfo.Initialize();
                        searchParams.Initialize();

                        // Access radio information
                        uint getInfoError = NativeImports.BluetoothGetRadioInfo(hRadio, ref radioInfo);

                        // Success
                        if (getInfoError == 0)
                        {
                            // Set search parameters
                            searchParams.hRadio               = hRadio;
                            searchParams.fIssueInquiry        = true;
                            searchParams.fReturnUnknown       = true;
                            searchParams.fReturnConnected     = false;
                            searchParams.fReturnRemembered    = false;
                            searchParams.fReturnAuthenticated = false;
                            searchParams.cTimeoutMultiplier   = 2;

                            // Search for a device
                            found = NativeImports.BluetoothFindFirstDevice(ref searchParams, ref deviceInfo);

                            // Success
                            if (found != IntPtr.Zero)
                            {
                                do
                                {
                                    // Note: Switch Pro Controller is simply called "Pro Controller"
                                    if (deviceInfo.szName.StartsWith("Nintendo"))
                                    {
                                        Prompt("Found " + deviceInfo.szName);

                                        StringBuilder password  = new StringBuilder();
                                        uint          pcService = 16;
                                        Guid[]        guids     = new Guid[16];
                                        bool          success   = true;

                                        // Create Password out of BT radio MAC address
                                        var bytes = BitConverter.GetBytes(radioInfo.address);
                                        for (int i = 0; i < 6; i++)
                                        {
                                            password.Append((char)bytes[i]);
                                        }

                                        // Authenticate
                                        if (success)
                                        {
                                            var errAuth = NativeImports.BluetoothAuthenticateDevice(IntPtr.Zero, hRadio, ref deviceInfo, password.ToString(), 6);
                                            success = errAuth == 0;
                                        }

                                        // Install PC Service
                                        if (success)
                                        {
                                            var errService = NativeImports.BluetoothEnumerateInstalledServices(hRadio, ref deviceInfo, ref pcService, guids);
                                            success = errService == 0;
                                        }

                                        // Set to HID service
                                        if (success)
                                        {
                                            var errActivate = NativeImports.BluetoothSetServiceState(hRadio, ref deviceInfo, ref HidServiceClass, 0x01);
                                            success = errActivate == 0;
                                        }

                                        if (success)
                                        {
                                            Prompt("Successfully Paired!");
                                            Count += 1;
                                        }
                                        else
                                        {
                                            Prompt("Failed to Pair.");
                                        }
                                    }
                                } while (NativeImports.BluetoothFindNextDevice(found, ref deviceInfo));
                            }
                        }
                        else
                        {
                            // Failed to get BT Radio info
                        }
                    }

                    NativeImports.CloseHandle(hRadio);

                    // Repeat commands if more BT Radio's exist
                } while (NativeImports.BluetoothFindNextRadio(ref hFind, out hRadio));

                //close hFind that was used with BluetoothFindNextRadio()
                NativeImports.BluetoothFindRadioClose(hFind);
            }
            else
            {
                // No (compatable) Bluetooth
                SetPrompt(
                    "No compatable Bluetooth Radios found." +
                    Environment.NewLine +
                    "This only works for the Microsoft Bluetooth Stack.");
                _notCompatable = true;
                return;
            }

            // Close this window
            Dispatcher.BeginInvoke((Action)(() => Close()));
        }
        public static void RemoveAllWiimotes()
        {
            WiitarDebug.Log("FUNC BEGIN - RemoveAllWiimotes");

            var           radioParams     = new NativeImports.BLUETOOTH_FIND_RADIO_PARAMS();
            Guid          HidServiceClass = Guid.Parse(NativeImports.HID_GUID);
            List <IntPtr> btRadios        = new List <IntPtr>();
            IntPtr        foundRadio;
            IntPtr        foundResult;

            radioParams.Initialize();

            // Get first BT Radio
            foundResult = NativeImports.BluetoothFindFirstRadio(ref radioParams, out foundRadio);
            bool more = foundResult != IntPtr.Zero;

            do
            {
                if (foundRadio != IntPtr.Zero)
                {
                    btRadios.Add(foundRadio);
                }

                // Find more
                more = NativeImports.BluetoothFindNextRadio(ref radioParams, out foundRadio);
            } while (more);

            if (btRadios.Count > 0)
            {
                foreach (var radio in btRadios)
                {
                    IntPtr found;
                    var    radioInfo    = new NativeImports.BLUETOOTH_RADIO_INFO();
                    var    deviceInfo   = new NativeImports.BLUETOOTH_DEVICE_INFO();
                    var    searchParams = new NativeImports.BLUETOOTH_DEVICE_SEARCH_PARAMS();

                    radioInfo.Initialize();
                    deviceInfo.Initialize();
                    searchParams.Initialize();

                    // Access radio information
                    WiitarDebug.Log("BEF - BluetoothGetRadioInfo");
                    uint getInfoError = NativeImports.BluetoothGetRadioInfo(radio, ref radioInfo);
                    WiitarDebug.Log("AFT - BluetoothGetRadioInfo");

                    if (getInfoError == 0)
                    {
                        // Set search parameters
                        searchParams.hRadio               = radio;
                        searchParams.fIssueInquiry        = true;
                        searchParams.fReturnUnknown       = true;
                        searchParams.fReturnConnected     = true;
                        searchParams.fReturnRemembered    = true;
                        searchParams.fReturnAuthenticated = true;
                        searchParams.cTimeoutMultiplier   = 2;

                        // Search for a device
                        WiitarDebug.Log("BEF - BluetoothFindFirstDevice");
                        found = NativeImports.BluetoothFindFirstDevice(ref searchParams, ref deviceInfo);
                        WiitarDebug.Log("AFT - BluetoothFindFirstDevice");

                        // Success
                        if (found != IntPtr.Zero)
                        {
                            do
                            {
                                if (deviceInfo.szName.StartsWith("Nintendo RVL-CNT-01"))
                                {
                                    //NativeImports.BluetoothRemoveDevice(ref deviceInfo.Address);

                                    //StringBuilder password = new StringBuilder();
                                    ////uint pcService = 16;
                                    ////Guid[] guids = new Guid[16];
                                    bool success   = true;
                                    uint errForget = 0;

                                    if (/*!ConnectedDeviceAddresses.Contains(deviceInfo.Address) && */ (deviceInfo.fRemembered || deviceInfo.fConnected))
                                    {
                                        WiitarDebug.Log("BEF - BluetoothRemoveDevice");
                                        errForget = NativeImports.BluetoothRemoveDevice(ref deviceInfo.Address);
                                        WiitarDebug.Log("AFT - BluetoothRemoveDevice");
                                        success = errForget == 0;
                                    }

#if DEBUG
                                    if (!success)
                                    {
                                        MessageBox.Show("DEBUG - Failed to remove bluetooth device.");
                                    }
#endif
                                }
                            } while (NativeImports.BluetoothFindNextDevice(found, ref deviceInfo));
                        }
                    }
                }
            }

            WiitarDebug.Log("FUNC END - RemoveAllWiimotes");
        }
        public void Sync()
        {
            var           radioParams     = new NativeImports.BLUETOOTH_FIND_RADIO_PARAMS();
            Guid          HidServiceClass = Guid.Parse(NativeImports.HID_GUID);
            List <IntPtr> btRadios        = new List <IntPtr>();
            IntPtr        foundRadio;
            IntPtr        handle;

            radioParams.Initialize();

            // Get first BT Radio
            handle = NativeImports.BluetoothFindFirstRadio(ref radioParams, out foundRadio);
            bool more = handle != IntPtr.Zero;

            if (!more)
            {
                uint findBtError = NativeImports.GetLastError();
                Prompt("Error Code " + findBtError.ToString());
            }

            do
            {
                if (foundRadio != IntPtr.Zero)
                {
                    btRadios.Add(foundRadio);
                }

                // Find more
                more = NativeImports.BluetoothFindNextRadio(ref handle, out foundRadio);
            } while (more);

            if (btRadios.Count > 0)
            {
                Prompt("Searching for controllers...");

                // Search until cancelled or at least one device is paired
                while (Count == 0 && !Cancelled)
                {
                    foreach (var radio in btRadios)
                    {
                        IntPtr found;
                        var    radioInfo    = new NativeImports.BLUETOOTH_RADIO_INFO();
                        var    deviceInfo   = new NativeImports.BLUETOOTH_DEVICE_INFO();
                        var    searchParams = new NativeImports.BLUETOOTH_DEVICE_SEARCH_PARAMS();

                        radioInfo.Initialize();
                        deviceInfo.Initialize();
                        searchParams.Initialize();

                        // Access radio information
                        uint getInfoError = NativeImports.BluetoothGetRadioInfo(radio, ref radioInfo);

                        // Success
                        if (getInfoError == 0)
                        {
                            // Set search parameters
                            searchParams.hRadio               = radio;
                            searchParams.fIssueInquiry        = true;
                            searchParams.fReturnUnknown       = true;
                            searchParams.fReturnConnected     = false;
                            searchParams.fReturnRemembered    = false;
                            searchParams.fReturnAuthenticated = false;
                            searchParams.cTimeoutMultiplier   = 2;

                            // Search for a device
                            found = NativeImports.BluetoothFindFirstDevice(ref searchParams, ref deviceInfo);

                            // Success
                            if (found != IntPtr.Zero)
                            {
                                do
                                {
                                    // Note: Switch Pro Controller is simply called "Pro Controller"
                                    // Note: The Wiimote MotionPlus reveals its name only after BT authentication
                                    var probeUnnamed = String.IsNullOrEmpty(deviceInfo.szName);
                                    if (probeUnnamed || deviceInfo.szName.StartsWith(SyncWindow.deviceNameMatch))
                                    {
                                        if (!probeUnnamed)
                                        {
                                            Prompt("Found " + deviceInfo.szName);
                                        }

                                        StringBuilder password  = new StringBuilder();
                                        uint          pcService = 16;
                                        Guid[]        guids     = new Guid[16];
                                        bool          success   = true;

                                        // Create Password out of BT radio MAC address
                                        var bytes = BitConverter.GetBytes(radioInfo.address);
                                        for (int i = 0; i < 6; i++)
                                        {
                                            password.Append((char)bytes[i]);
                                        }

                                        // Authenticate
                                        if (success)
                                        {
                                            var errAuth = NativeImports.BluetoothAuthenticateDevice(IntPtr.Zero, radio, ref deviceInfo, password.ToString(), 6);
                                            success = errAuth == 0;
                                            if (probeUnnamed)
                                            {
                                                if (String.IsNullOrEmpty(deviceInfo.szName) || !deviceInfo.szName.StartsWith(SyncWindow.deviceNameMatch))
                                                {
                                                    continue;
                                                }
                                                else if (success)
                                                {
                                                    probeUnnamed = false;
                                                    Prompt("Found " + deviceInfo.szName);
                                                }
                                            }
                                        }

                                        // Install PC Service
                                        if (success)
                                        {
                                            var errService = NativeImports.BluetoothEnumerateInstalledServices(radio, ref deviceInfo, ref pcService, guids);
                                            success = errService == 0;
                                        }

                                        // Set to HID service
                                        if (success)
                                        {
                                            var errActivate = NativeImports.BluetoothSetServiceState(radio, ref deviceInfo, ref HidServiceClass, 0x01);
                                            success = errActivate == 0;
                                        }

                                        if (success)
                                        {
                                            Prompt("Successfully Paired!");
                                            Count += 1;
                                        }
                                        else if (!probeUnnamed)
                                        {
                                            Prompt("Failed to Pair.");
                                        }
                                    }
                                } while (NativeImports.BluetoothFindNextDevice(found, ref deviceInfo));
                            }
                        }
                        else
                        {
                            // Failed to get BT Radio info
                        }
                    }
                }

                // Close each Radio
                foreach (var openRadio in btRadios)
                {
                    NativeImports.CloseHandle(openRadio);
                }
            }
            else
            {
                // No (compatable) Bluetooth
                SetPrompt(
                    "No compatable Bluetooth Radios found." +
                    Environment.NewLine +
                    "This only works for the Microsoft Bluetooth Stack.");
                _notCompatable = true;
                return;
            }

            // Close this window
            Dispatcher.BeginInvoke((Action)(() => Close()));
        }