//int index = listViewDevices.SelectedIndices[0]; #region Connect private void button2_Click(object sender, EventArgs e) { if (listViewDevices.SelectedItems.Count > 0) { EventHandler <BluetoothWin32AuthenticationEventArgs> authHandler = new EventHandler <BluetoothWin32AuthenticationEventArgs>(handleAuthRequests); BluetoothWin32Authentication authenticator = new BluetoothWin32Authentication(authHandler); BluetoothDeviceInfo selectedDevice = devices[listViewDevices.SelectedIndices[0]]; if (MessageBox.Show(String.Format("Would you like to attempt to pair with {0}?", selectedDevice.DeviceName), "Pair Device", MessageBoxButtons.YesNo) == DialogResult.Yes) { if (BluetoothSecurity.PairRequest(selectedDevice.DeviceAddress, null)) { MessageBox.Show("We paired!"); } else { MessageBox.Show("Failed to pair!"); } } } else { MessageBox.Show("Select a Device to Pair"); } }
/// <summary> /// This function revokes the personal identification number (PIN) for the Bluetooth device. /// </summary> /// <remarks><para>On Windows CE platforms this calls <c>BthRevokePIN</c>, /// its MSDN remarks say: /// </para> /// <para>“When the PIN is revoked, it is removed from registry. /// The active connection to the device is not necessary, nor is the presence /// of the Bluetooth controller.” /// </para> /// <para>On Windows CE platforms this removes any pending BluetoothWin32Authentication object but does not remove the PIN for an already authenticated device. /// Use RemoveDevice to ensure a pairing is completely removed.</para> /// <para>See also /// <see cref="M:InTheHand.Net.Bluetooth.BluetoothSecurity.SetPin(InTheHand.Net.BluetoothAddress,System.String)"/> /// </para> /// </remarks> /// <param name="device">The remote device.</param> /// <returns>True on success, else False.</returns> /// <seealso cref="M:InTheHand.Net.Bluetooth.BluetoothSecurity.SetPin(InTheHand.Net.BluetoothAddress,System.String)"/> public bool RevokePin(BluetoothAddress device) { if (device == null) { throw new ArgumentNullException("device"); } #if NETCF int result = NativeMethods.BthRevokePIN(device.ToByteArray()); if (result != 0) { int error = Marshal.GetLastWin32Error(); return(false); } return(true); #else if (authenticators.ContainsKey(device)) { BluetoothWin32Authentication bwa = (BluetoothWin32Authentication)authenticators[device]; authenticators.Remove(device); bwa.Dispose(); return(true); } return(false); //throw new PlatformNotSupportedException("Use RemoveDevice to remove a pairing with a device from Windows XP"); #endif }
public MainForm() { InitializeComponent(); bluetoothAuthenticationHandler_ = new EventHandler <BluetoothWin32AuthenticationEventArgs>(HandleBluetoothAuthenticationRequests); bluetoothWin32Authentication_ = new BluetoothWin32Authentication(bluetoothAuthenticationHandler_); bluetoothClient_ = new BluetoothClient(); }
private void btnBTAuto_Click(object sender, EventArgs e) { if (this._win32Auth == null) { this.authTextbox("自动配对......."); this.start_auth_open(); this._win32Auth = new BluetoothWin32Authentication(new Action <string, string>(this.bthAuthCallback), new Action <string, bool>(this.bthAuthResult)); } }
private void PairTask(CancellationToken token) { // Setup automatic authentication BluetoothWin32Authentication auth = new BluetoothWin32Authentication(OnHandleRequests); while (!token.IsCancellationRequested) { PairLoop(token); } }
public void BtWin32Auth() { bool useMsgBox = console.ReadYesNo("Auth callback prompt dialog", false); var hndlr = useMsgBox ? (EventHandler <BluetoothWin32AuthenticationEventArgs>)HandlerWithMsgBoxInclSsp //HndlrWithMsgBox : HndlrNoRespond; using (BluetoothWin32Authentication ar = new BluetoothWin32Authentication(hndlr)) { console.Pause("Continue to stop authenticating>"); } }
/// <summary> /// Connects the client to a remote Bluetooth host using the specified mac address and OnConnected handler. /// </summary> /// <param name="mac">The mac address of the remote host.</param> /// <param name="handler">The delegate to handle connecting event.</param> /// <returns>true if the BluetoothAdapter was connected to a remote resource; otherwise, false.</returns> public bool Connect(string mac, OnConnected handler) { BluetoothAddress bta = new BluetoothAddress(Convert.ToInt64(mac, 16)); BluetoothEndPoint rep = new BluetoothEndPoint(bta, BluetoothService.SerialPort); lock ( mConnLock ) { try { if ((Connected && !ALLOW_OTHER_CONNECTION) || !ValidateAddress(mac)) { return(false); } Disconnect(); RemovePairedDevice(mac); EventHandler <BluetoothWin32AuthenticationEventArgs> authHandler = new EventHandler <BluetoothWin32AuthenticationEventArgs>(handleRequests); BluetoothWin32Authentication authenticator = new BluetoothWin32Authentication(authHandler); // 페어링 요청 BluetoothSecurity.PairRequest(bta, null); mBtClient = new BluetoothClient(); mBtClient.Connect(rep); authenticator.Dispose(); DeviceClass = DeviceClass != 0 ? DeviceClass : FindDeviceClass(mac); if (DeviceClass == 0) { mBtClient.Dispose(); return(false); } WriteDeviceClass(mac, DeviceClass); DeviceAddress = mac; handler(DeviceClass); } catch { return(false); } return(true); } }
public Form_main() { InitializeComponent(); // BluetoothClient オブジェクトの生成 bc = new BluetoothClient(); // 未ペアリングデバイスを探索する際の所要時間を設定。デフォルトは10秒。 bc.InquiryLength = new TimeSpan(0, 0, 5); // この場合は5秒 // 非同期BluetoothClient オブジェクトの生成 bcAsync = new BluetoothClient(); // 未ペアリングデバイスを探索する際の所要時間を設定。デフォルトは10秒。 bcAsync.InquiryLength = new TimeSpan(0, 0, 2); // この場合は5秒 // ペアリングリクエストが発生した場合、引数のメソッドをコールバックする。 BluetoothWin32Authentication authenticator = new BluetoothWin32Authentication(Win32AuthCallbackHandler); }
public bool PairingTo(BluetoothDeviceInfo device) { if (!device.Authenticated) { //device.SetServiceState(BluetoothService.Handsfree, true); _win32Auth = new BluetoothWin32Authentication(HandleWin32Auth); localClient.SetPin(DEVICE_PIN); //localClient.SetPin(device.DeviceAddress, DEVICE_PIN); // replace DEVICE_PIN here, synchronous method, but fast return(BluetoothSecurity.PairRequest(device.DeviceAddress, DEVICE_PIN)); } return(true); }
//#endif #region Set PIN /// <summary> /// This function stores the personal identification number (PIN) for the Bluetooth device. /// </summary> /// <param name="device">Address of remote device.</param> /// <param name="pin">Pin, alphanumeric string of between 1 and 16 ASCII characters.</param> /// <remarks><para>On Windows CE platforms this calls <c>BthSetPIN</c>, /// its MSDN remarks say: /// </para> /// <para>“Stores the pin for the Bluetooth device identified in pba. /// The active connection to the device is not necessary, nor is the presence /// of the Bluetooth controller. The PIN is persisted in the registry until /// BthRevokePIN is called. /// </para> /// <para>“While the PIN is stored, it is supplied automatically /// after the PIN request is issued by the authentication mechanism, so the /// user will not be prompted for it. Typically, for UI-based devices, you /// would set the PIN for the duration of authentication, and then revoke /// it after authentication is complete.” /// </para> /// <para>See also /// <see cref="M:InTheHand.Net.Bluetooth.BluetoothSecurity.RevokePin(InTheHand.Net.BluetoothAddress)"/> /// </para> /// </remarks> /// <returns>True on success, else False.</returns> /// <seealso cref="M:InTheHand.Net.Bluetooth.BluetoothSecurity.RevokePin(InTheHand.Net.BluetoothAddress)"/> public bool SetPin(BluetoothAddress device, string pin) { if (device == null) { throw new ArgumentNullException("device"); } if (pin == null) { throw new ArgumentNullException("pin"); } #if NETCF if (pin.Length < 1 | pin.Length > 16) { throw new ArgumentException("Pin must be between 1 and 16 characters long."); } byte[] pinbytes = System.Text.Encoding.ASCII.GetBytes(pin); int len = pin.Length; int result = NativeMethods.BthSetPIN(device.ToByteArray(), len, pinbytes); if (result != 0) { int error = Marshal.GetLastWin32Error(); return(false); } return(true); #else //remove existing listener if (authenticators.ContainsKey(device)) { BluetoothWin32Authentication bwa = (BluetoothWin32Authentication)authenticators[device]; authenticators.Remove(device); bwa.Dispose(); } authenticators.Add(device, new BluetoothWin32Authentication(device, pin)); return(true); //else //{ // throw new PlatformNotSupportedException("Use PairRequest to pair with a device from Windows XP"); //} #endif }
public WindowsBluetoothAdapter() { // set win32 bluetooth stack auth callback that to always confirms inbound conns bluetoothWin32Authentication = new BluetoothWin32Authentication(Handler); listener = new BluetoothListener(CAMPFIRE_NET_SERVICE_CLASS); listener.Authenticate = false; listener.Encrypt = false; new Thread(() => { listener.Start(); while (true) { var client = listener.AcceptBluetoothClient(); Console.WriteLine("Warning: Windows client doesn't support accepting!"); Console.WriteLine($"Got {client.RemoteMachineName} {client.RemoteEndPoint}"); } }).Start(); }
// Funkcja która łączy adapter z urządzeniem bluetooth public void Connect(ListBox devices) { // Pobranie informacji o wybranym urządzeniu BluetoothDeviceInfo device = info[devices.SelectedIndex]; // Aktualizacja nazwy urządzenia device.Update(); // Odświeżenie informacji o urządzeniu device.Refresh(); // Przygotowanie urządzenia do wysyłania danych binarnych z wykorzystaniem protokołu OBEX device.SetServiceState(BluetoothService.ObexObjectPush, true); EventHandler <BluetoothWin32AuthenticationEventArgs> handler = new EventHandler <BluetoothWin32AuthenticationEventArgs>(HandleRequests); BluetoothWin32Authentication auth = new BluetoothWin32Authentication(handler); // Jeżeli urządzenie nie jest sparowane zostaje wysłana prośba o sparowanie, musi zostać ona potwierdzona podaniem pinu - 123456 if (!device.Authenticated) { BluetoothSecurity.PairRequest(device.DeviceAddress, "123456"); } }
private void ConnectButton_Click(object sender, RoutedEventArgs e) { EventHandler <BluetoothWin32AuthenticationEventArgs> authHandler = new EventHandler <BluetoothWin32AuthenticationEventArgs>(handleAuthRequests); BluetoothWin32Authentication authenticator = new BluetoothWin32Authentication(authHandler); if (adapter == null || device == null) { MessageBox.Show("You didnt choose adapter or device!"); return; } if (BluetoothSecurity.PairRequest(device.DeviceAddress, null)) { ConnectButton.IsEnabled = false; DisconnectButton.IsEnabled = true; SendFileButton.IsEnabled = true; MessageBox.Show("Connected successfully with " + device.DeviceName); return; } MessageBox.Show("Couldn't connect to " + device.DeviceName); }
private void Window_Loaded(object sender, RoutedEventArgs e) { handler = new EventHandler <BluetoothWin32AuthenticationEventArgs>(HandleRequests); auth = new BluetoothWin32Authentication(handler); InitBluetooth(); }
private void BthConnectBtn_Click(object sender, EventArgs e) { BluetoothClient client = new BluetoothClient(); BluetoothDeviceInfo[] devices = client.DiscoverDevices(); BluetoothDeviceInfo device = null; foreach (BluetoothDeviceInfo d in devices) { RecvBoxAddText = d.DeviceName + "\r\n"; if (d.DeviceName == "HUAWEI P30") { device = d; break; } } if (device != null) { RecvBoxAddText = String.Format("Name:{0} Address:{1:C}", device.DeviceName, device.DeviceAddress); try { //BluetoothClient client = new BluetoothClient(this.CreateNewEndpoint(localAddress)); //BluetoothEndPoint ep = this.CreateNewEndpoint(device.DeviceAddress); EventHandler <BluetoothWin32AuthenticationEventArgs> handler = new EventHandler <BluetoothWin32AuthenticationEventArgs>(HandleRequests); BluetoothWin32Authentication auth = new BluetoothWin32Authentication(handler); BluetoothSecurity.PairRequest(device.DeviceAddress, null); } catch { return; } client.Connect(device.DeviceAddress, BluetoothService.SerialPort); Stream peerStream = client.GetStream(); // Create storage for receiving data byte[] buffer = new byte[2000]; // Read Data peerStream.Read(buffer, 0, 50); // Convert Data to String string data = System.Text.ASCIIEncoding.ASCII.GetString(buffer, 0, 50); RecvBoxAddText = "Receiving data: " + data; int i = 0; while (true) { RecvBoxAddText = "Writing: " + i.ToString(); byte[] dataBuffer = System.Text.ASCIIEncoding.ASCII.GetBytes(i.ToString()); peerStream.Write(dataBuffer, 0, dataBuffer.Length); ++i; if (i >= int.MaxValue) { i = 0; } Thread.Sleep(500); } } }