コード例 #1
1
        private void search()
        {
            try
            {
                Guid uuid = BluetoothService.L2CapProtocol;
                BluetoothDeviceInfo bdi;
                BluetoothAddress ba;
                byte tmp;
                bool found = false;
                int discarded;

                bc = new BluetoothClient();

                bc.InquiryLength = new TimeSpan(0, 0, 0, Int32.Parse(osae.GetObjectPropertyValue(pName, "Discover Length").Value), 0);
                nearosaeDevices = bc.DiscoverDevices(10, false, false, true);

                for (int j = 0; j < nearosaeDevices.Length; j++)
                {
                    string addr = nearosaeDevices[j].DeviceAddress.ToString();

                    Object obj = osae.GetObjectByAddress(addr);

                    if (obj == null)
                    {
                        if (osae.GetObjectPropertyValue(pName, "Learning Mode").Value == "TRUE")
                        {
                            osae.ObjectAdd(nearosaeDevices[j].DeviceName, nearosaeDevices[j].DeviceName, "BLUETOOTH DEVICE", nearosaeDevices[j].DeviceAddress.ToString(), "", true);
                            osae.ObjectPropertySet(nearosaeDevices[j].DeviceName, "Discover Type", "0");
                            logging.AddToLog(addr + " - " + nearosaeDevices[j].DeviceName + ": added to OSA", true);
                        }
                    }
                }

                List<OSAEObject> objects = osae.GetObjectsByType("BLUETOOTH DEVICE");

                foreach (OSAEObject obj in objects)
                {
                    found = false;
                    string address = obj.Address;
                    byte[] byteArray = HexEncoding.GetBytes(address, out discarded);
                    tmp = byteArray[0];
                    byteArray[0] = byteArray[5];
                    byteArray[5] = tmp;
                    tmp = byteArray[1];
                    byteArray[1] = byteArray[4];
                    byteArray[4] = tmp;
                    tmp = byteArray[2];
                    byteArray[2] = byteArray[3];
                    byteArray[3] = tmp;
                    ba = new BluetoothAddress(byteArray);
                    bdi = new BluetoothDeviceInfo(ba);
                    logging.AddToLog("begin search for " + address, false);

                    for (int j = 0; j < nearosaeDevices.Length; j++)
                    {
                        if (nearosaeDevices[j].DeviceAddress.ToString() == address)
                        {
                            found = true;
                            logging.AddToLog(address + " - " + obj.Name + ": found with DiscoverDevices", false);
                        }
                    }
                    if (!found)
                    {
                        logging.AddToLog(address + " - " + obj.Name + ": failed with DiscoverDevices", false);

                    }

                    try
                    {
                        if (!found && (Int32.Parse(osae.GetObjectPropertyValue(obj.Name, "Discover Type").Value) == 2 || Int32.Parse(osae.GetObjectPropertyValue(obj.Name, "Discover Type").Value) == 0))
                        {
                            logging.AddToLog(address + " - " + obj.Name + ": attempting GetServiceRecords", false);

                            bdi.GetServiceRecords(uuid);
                            found = true;
                            logging.AddToLog(address + " - " + obj.Name + " found with GetServiceRecords", false);

                        }
                    }
                    catch (Exception ex)
                    {
                        logging.AddToLog(address + " - " + obj.Name + " failed GetServiceRecords. exception: " + ex.Message, false);

                    }

                    try
                    {
                        if (!found && (Int32.Parse(osae.GetObjectPropertyValue(obj.Name, "Discover Type").Value) == 3 || Int32.Parse(osae.GetObjectPropertyValue(obj.Name, "Discover Type").Value) == 0))
                        {
                            logging.AddToLog(address + " - " + obj.Name + ": attempting Connection", false);
                            //attempt a connect
                            BluetoothEndPoint ep;
                            ep = new BluetoothEndPoint(bdi.DeviceAddress, BluetoothService.Handsfree);
                            //MessageBox.Show("attempt connect: " + pairedDevices[i].DeviceAddress);
                            bc.Connect(ep);
                            logging.AddToLog(address + " - " + obj.Name + " found with Connect attempt", false);
                            bc.Close();
                            found = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        logging.AddToLog(address + " - " + obj.Name + " failed with Connect attempt. exception: " + ex.Message, false);
                    }

                    if (found)
                    {
                        osae.ObjectStateSet(obj.Name, "ON");
                        logging.AddToLog("Status Updated in osae", false);
                    }
                    else
                    {
                        osae.ObjectStateSet(obj.Name, "OFF");
                        logging.AddToLog("Status Updated in osae", false);
                    }

                }
            }
            catch (Exception ex)
            {
                logging.AddToLog("Error searching for devices: " + ex.Message, true);
            }
        }
コード例 #2
0
ファイル: BTUtils.cs プロジェクト: ArmyOfPirates/PS3BluMote
        public static void HibernatePS3Remote(bool checkBefore, string btAddress, BluetoothDeviceInfo dev)
        {
            BluetoothDeviceInfo device;
            if (dev == null && btAddress != null)
            {
                string addr = FormatBtAddress(btAddress, null, "N");
                if (addr.Length > 0) device = new BluetoothDeviceInfo(BluetoothAddress.Parse(btAddress));
                else device = null;
            }
            else if (dev != null) device = dev;
            else device = null;

            if (device != null)
            {
                if ((checkBefore && RemoteBtState(null, device) == RemoteBtStates.Awake) || !checkBefore)
                {
                    SetHIDServiceState(false, btAddress, device);
                    SetHIDServiceState(true, btAddress, device);
                }
            }
            else
            {
                DebugLog.write("BTUtils.HibernatePS3Remote can't create BluetoothDeviceInfo");
            }
        }
コード例 #3
0
		public override void connect ()
		{
			if (connection == null)
			{
                connection = new BluetoothClient();
			}
			if (connection.Connected)
			{
                throw new Exception("Connection is already opened");
			}
			connection.Connect (new BluetoothAddress(bluetoothAddress), OtherData.upsBluetoothGuid);
            connectedDeviceInfo = new BluetoothDeviceInfo(connection.RemoteEndPoint.Address);
            bluetoothAddress = connection.RemoteEndPoint.Address.ToInt64();

            socket = connection.Client;
            socketReciveOperation = new SocketAsyncEventArgs();
            socketReciveOperation.UserToken = socket;
            socketReciveOperation.RemoteEndPoint = socket.RemoteEndPoint;
            socketReciveOperation.Completed += new EventHandler<SocketAsyncEventArgs>(onReciveComplete);

            socketSendOperation = new SocketAsyncEventArgs();
            socketSendOperation.UserToken = socket;
            socketSendOperation.RemoteEndPoint = socket.RemoteEndPoint;
            socketSendOperation.Completed += new EventHandler<SocketAsyncEventArgs>(onSendComplete);
            
            WinBluetoothFactory.getFactory().addConnectedDevice(this);
		}
コード例 #4
0
 MyDeviceInfo(BluetoothDeviceInfo btInfo)
 {
     this.Authenticated = btInfo.Authenticated;
     this.ClassOfDevice = btInfo.ClassOfDevice;
     this.Connected     = btInfo.Connected;
     this.DeviceAddress = btInfo.DeviceAddress;
     this.DeviceName    = btInfo.DeviceName;
 }
コード例 #5
0
 public Form6(BluetoothDeviceInfo wocket)
 {
     InitializeComponent();
     this.wocket        = wocket;
     this.textBox1.Text = wocket.DeviceName;
     this.textBox2.Text = wocket.DeviceAddress.ToString();
     this.Text          = "Wocket (" + wocket.DeviceAddress.ToString() + ")";
 }
コード例 #6
0
ファイル: Form6.cs プロジェクト: katadam/wockets
 public Form6(BluetoothDeviceInfo wocket)
 {
     InitializeComponent();
     this.wocket = wocket;
     this.textBox1.Text = wocket.DeviceName;
     this.textBox2.Text = wocket.DeviceAddress.ToString();
     this.Text = "Wocket (" +wocket.DeviceAddress.ToString() + ")";
 }
コード例 #7
0
            public BdiListViewItem(BluetoothDeviceInfo device)
                : base(device.DeviceName)
            {
#if NETCF
                ImageIndex = 0;
#endif
                m_bdi = device;
            }
コード例 #8
0
ファイル: ConnectedSphero.cs プロジェクト: jihlee/BallControl
 public ConnectedSphero(BluetoothDeviceInfo peerInformation, NetworkStream spheroSocket)
     : base(peerInformation)
 {
     _spheroSocketWrapper = new StreamSocketWrapper(spheroSocket);
     _runner = new AwaitingConnectedSpheroRunner(_spheroSocketWrapper);
     _runner.Disconnected += (sender, args) => RaiseDisconnected();
     _runner.Start();
 }
コード例 #9
0
        static void Connect(bool onlyPair = false)
        {
            bool connected = false;

            while (!connected)
            {
                try
                {
                    bluetoothClient = new BluetoothClient();

                    BluetoothDeviceInfo hcInfo = new BluetoothDeviceInfo(new BluetoothAddress(0));

                    while (!hcFound)
                    {
                        var devices = bluetoothClient.DiscoverDevices();
                        foreach (var device in devices)
                        {
                            if (device.DeviceName.Equals("HC-05"))
                            {
                                hcInfo = device;
                                Console.WriteLine("Bluetooth-Empfänger gefunden");
                                hcFound = true;
                                break;
                            }
                        }
                        if (!hcFound)
                        {
                            Console.WriteLine("Bluetooth-Empfänger wurde nicht gefunden, suche erneut...");
                        }
                    }

                    bool paired = false;
                    while (!paired)
                    {
                        paired = BluetoothSecurity.PairRequest(hcInfo.DeviceAddress, "1234");
                        if (paired)
                        {
                            Console.WriteLine("Bluetooth-Empfänger erfolgreich gepaart");
                        }
                        else
                        {
                            Console.WriteLine("Bluetooth-Empfänger konnte nicht gepaart werden");
                        }
                    }

                    Guid             serviceClass = BluetoothService.SerialPort;
                    BluetoothAddress addr         = BluetoothAddress.Parse(hcInfo.DeviceAddress.ToString());
                    var endpoint = new BluetoothEndPoint(addr, serviceClass);
                    bluetoothClient.Connect(endpoint);
                    connected = true;
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    connected = false;
                }
            }
        }
コード例 #10
0
ファイル: MyBluetooth.cs プロジェクト: RealBigTree/NetDemo
 public void Connect(BluetoothDeviceInfo Device)
 {
     try {
         CurrentDevices = Device;
         //Blueclient.SetPin(Device.DeviceAddress, null);
         //Blueclient.Connect(Device.DeviceAddress, BluetoothService.Handsfree);
     } catch (Exception ex) {
     }
 }
コード例 #11
0
ファイル: PairingSupport.cs プロジェクト: ayumax/WpfBluetooth
        public void RemovePair(BluetoothDeviceInfo device)
        {
            if (device == null)
            {
                return;
            }

            BluetoothSecurity.RemoveDevice(device.DeviceAddress);
        }
コード例 #12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DeviceInfo"/> class.
 /// </summary>
 /// <param name="deviceInfo">The device information.</param>
 internal DeviceInfo(BluetoothDeviceInfo deviceInfo)
 {
     DeviceName          = deviceInfo.DeviceName;
     IsKnown             = deviceInfo.Remembered;
     SignalStrength      = deviceInfo.Rssi;
     LastSeen            = deviceInfo.LastSeen;
     LastUsed            = deviceInfo.LastUsed;
     BluetoothDeviceInfo = deviceInfo;
 }
コード例 #13
0
        public static void PrintDevice(BluetoothDeviceInfo device)
        {
            // log and save all found devices

            Console.Write(device.DeviceName + " (" + device.DeviceAddress + "): Device is ");
            Console.Write(device.Remembered ? "remembered" : "not remembered");
            Console.Write(device.Authenticated ? ", paired" : ", not paired");
            Console.WriteLine(device.Connected ? ", connected" : ", not connected");
        }
コード例 #14
0
        /// <summary>
        /// ペアリングボタンクリック
        /// listBoxNonPairで選択されているデバイスとペアリングを実施。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_pairing_Click(object sender, EventArgs e)
        {
            BluetoothDeviceInfo deviceInfo = (BluetoothDeviceInfo)listBoxNonPair.SelectedItem;

            if (deviceInfo != null)
            {
                Pairing(deviceInfo);
            }
        }
コード例 #15
0
        /// <summary>
        /// removeボタンクリック
        /// listBoxPairedで選択されているデバイスとペアリングを解除する
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_remove_Click(object sender, EventArgs e)
        {
            BluetoothDeviceInfo deviceInfo = (BluetoothDeviceInfo)listBoxPaired.SelectedItem;

            if (deviceInfo != null)
            {
                RemovePairing(deviceInfo);
            }
        }
コード例 #16
0
ファイル: MainWindow.xaml.cs プロジェクト: kraugug/Bluetooth
        private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            BluetoothDeviceInfo device = (sender as ListView).SelectedItem as BluetoothDeviceInfo;

            if (device != null && device.Connected)
            {
                device.ShowDialog();
            }
        }
コード例 #17
0
        public void Connect(BluetoothDeviceInfo device)
        {
            LocalClient.Connect(device.DeviceAddress, ProfileID);

            ConnectedDevice = device;


            OnConnected();
        }
コード例 #18
0
 /// <summary>
 /// if the name didn't come in yet we get an address
 /// formatted like "F4:FC:32:1B:1F:16".  if the given
 /// device has a name of that format, ask for it again
 /// </summary>
 /// <param name="device"></param>
 /// <returns></returns>
 public string GetDeviceName(BluetoothDeviceInfo device)
 {
     if (device.DeviceName.IsBluetoothAddress())
     {
         System.Threading.Thread.Sleep(1000);
         device.Refresh();
     }
     return(device.DeviceName);
 }
コード例 #19
0
 private void RemoveDevice(BluetoothDeviceInfo device, CancellationToken token)
 {
     token.WaitHandle.WaitOne(1000);
     if (BluetoothSecurity.RemoveDevice(device.DeviceAddress))
     {
         Trace.WriteLine($"Wiimote removed: {device.DeviceAddress.ToMacAddress()}");
         token.WaitHandle.WaitOne(2000);
     }
 }
コード例 #20
0
    public void UnBondBluetoothDevice(BluetoothDeviceInfo bluetooth)
    {
#if UNITY_ANDROID && !UNITY_EDITOR
        if (InterfaceObj != null)
        {
            InterfaceObj.Call("unbond", bluetooth.obj);
        }
#endif
    }
コード例 #21
0
        /// <summary>
        /// Called when a custom pairing is initiated so that we can handle its custom ceremony
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        public async void PairingRequestedHandlerAsync(DeviceInformationCustomPairing sender, DevicePairingRequestedEventArgs args)
        {
            LogService.Write((Enum.GetName(typeof(DevicePairingKinds), args.PairingKind)), LoggingLevel.Information);

            BluetoothDeviceInfo currentDevice = new BluetoothDeviceInfo(args.DeviceInformation);

            // Save the args for use in ProvidePin case
            _pairingRequestedArgs = args;

            // Save the deferral away and complete it where necessary.
            if (args.PairingKind != DevicePairingKinds.DisplayPin)
            {
                _deferral = args.GetDeferral();
            }

            switch (args.PairingKind)
            {
            // Windows itself will pop the confirmation dialog as part of "consent" depending on which operating OS is running
            case DevicePairingKinds.ConfirmOnly:
            {
                var confirmationMessage = string.Format(BluetoothConfirmOnlyText, args.DeviceInformation.Name, args.DeviceInformation.Id);
                if (await DisplayMessagePanel(confirmationMessage, MessageType.InformationalMessage))
                {
                    AcceptPairing();
                }
            }
            break;

            // We only show the PIN on this side. The ceremony is actually completed when the user enters the PIN on the target device.
            case DevicePairingKinds.DisplayPin:
            {
                var confirmationMessage = string.Format(BluetoothDisplayPINText, args.Pin);
                await DisplayMessagePanel(confirmationMessage, MessageType.OKMessage);
            }
            break;

            // A PIN may be shown on the target device and the user needs to enter the matching PIN on the originating device.
            case DevicePairingKinds.ProvidePin:
            {
                _inProgressPairButton.Flyout = _savedPairButtonFlyout;
                _inProgressPairButton.Flyout.ShowAt(_inProgressPairButton);
            }
            break;

            // We show the PIN here and the user responds with whether the PIN matches what is displayed on the target device.
            case DevicePairingKinds.ConfirmPinMatch:
            {
                var confirmationMessage = string.Format(BluetoothConfirmPINMatchText, args.Pin);
                if (await DisplayMessagePanel(confirmationMessage, MessageType.YesNoMessage))
                {
                    AcceptPairing();
                }
            }
            break;
            }
        }
コード例 #22
0
        private void ConnectService()
        {
            allowBTConnection = true;
            BluetoothClient mClientBluetoothClient = new BluetoothClient();

            BluetoothDeviceInfo[] devices = mClientBluetoothClient.DiscoverDevices();
            BluetoothDeviceInfo   device  = null;

            foreach (BluetoothDeviceInfo d in devices)
            {
                if (d.DeviceAddress.ToString() == comboBoxBluetoothDevices.SelectedValue.ToString())
                {
                    device = d;
                    break;
                }
            }
            txtBTDeviceDetails.Text = txtBTDeviceDetails.Text + "Connect BT Service started!" + Environment.NewLine;
            if (device != null)
            {
                UpdateBTDeviceDetails(String.Format("Name:{0} Address:{1:C}", device.DeviceName, device.DeviceAddress));

                mClientBluetoothClient.Connect(device.DeviceAddress, BluetoothService.SerialPort);
                Stream peerStream = mClientBluetoothClient.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);
                UpdateBTDeviceDetails("Client -- Receiving data = " + data);

                int i = 0;
                while (allowBTConnection)
                {
                    UpdateBTDeviceDetails("Client -- Sending = " + i.ToString());
                    byte[] dataBuffer = System.Text.ASCIIEncoding.ASCII.GetBytes(i.ToString() + "\r\n");

                    peerStream.Write(dataBuffer, 0, dataBuffer.Length);
                    ++i;
                    if (i > 10)
                    {
                        i = 0;
                        allowBTConnection = false;
                        UpdateBTDeviceDetails("Client -- Close BT Service");
                    }
                    System.Threading.Thread.Sleep(500);
                }
                // Close network stream
                peerStream.Close();
                mClientBluetoothClient.Close();
            }
            Cursor.Current = Cursors.Default;
        }
コード例 #23
0
ファイル: Program.cs プロジェクト: disssection/GoMape
        static void Main(string[] args)
        {
            const string device_name = "JBL Pulse 2";

            BluetoothClient bluetoothClient = new BluetoothClient();

            IEnumerable <BluetoothDeviceInfo> targetDevices;

            Console.WriteLine("Discovering...");
            while (true)
            {
                var devices = bluetoothClient.DiscoverDevices();

                targetDevices = devices.Where(d => d.DeviceName == device_name);

                if (!targetDevices.Any())
                {
                    Console.WriteLine("No device by name JBL Pulse 2 found! Retrying...");
                }
                else
                {
                    break;
                }
            }
            if (targetDevices.Count() > 1)
            {
                Console.WriteLine("More than one Pulse 2 found! Picking one...");
            }
            BluetoothDeviceInfo pulse2 = targetDevices.First();

            Console.WriteLine(String.Format("Pulse 2 discovered, address is: {0}", pulse2.DeviceAddress));
            var targetAddress = pulse2.DeviceAddress;

            //new Guid("00001101-0000-1000-8000-00805F9B34FB")));
            bluetoothClient.Connect(targetAddress, BluetoothService.SerialPort);

            if (bluetoothClient.Connected)
            {
                Console.WriteLine("Connected to device's Serial Port");
            }

            while (true)
            {
                Console.WriteLine("Input color in sbyte");
                string s   = Console.ReadLine();
                int    val = int.Parse(s);
                //set bg color to smth
                sbyte[] cmd = new sbyte[] { -86, 88, 2, (sbyte)val, (sbyte)(0) };
                bluetoothClient.Client.Send(cmd.Select(b => (byte)b).ToArray());
            }


            bluetoothClient.Close();
            Console.WriteLine("Closing the client...");
            Console.ReadLine();
        }
コード例 #24
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Device"/> class.
 /// </summary>
 /// <param name="deviceInfo">
 /// The device_info.
 /// </param>
 public Device(BluetoothDeviceInfo deviceInfo)
 {
     if (deviceInfo != null)
     {
         DeviceInfo      = deviceInfo;
         IsAuthenticated = deviceInfo.Authenticated;
         IsConnected     = deviceInfo.Connected;
         DeviceName      = deviceInfo.DeviceName;
     }
 }
コード例 #25
0
        public RoboticsDeviceInfo(BluetoothDeviceInfo di)
        {
            this.Device        = di;
            this.DeviceName    = di.DeviceName;
            this.DeviceAddress = di.DeviceAddress;

            BTEndPoint = new BluetoothEndPoint(this.DeviceAddress, BluetoothService.SerialPort);

            connectedDelegate = this.Connected;
        }
コード例 #26
0
ファイル: Form5.cs プロジェクト: katadam/wockets
        public Form5(BluetoothDeviceInfo wocket)
        {
            InitializeComponent();

            //Copy parameters to loacal variables
            this.wocket = wocket;
            this.textBox1.Text = wocket.DeviceName;
            this.textBox2.Text = wocket.DeviceAddress.ToString();
            this.Text = "Wocket (" + wocket.DeviceAddress.ToString() + ")";
        }
コード例 #27
0
        public BluetoothDeviceInfo GetSelectedBtDevice()
        {
            BluetoothDeviceInfo devInfo = null;

            if (listViewDevices.SelectedItems.Count > 0)
            {
                devInfo = listViewDevices.SelectedItems[0].Tag as BluetoothDeviceInfo;
            }
            return(devInfo);
        }
コード例 #28
0
        public ParrotClient(BluetoothDeviceInfo device)
        {
            Device          = device;
            BluetoothClient = new BluetoothClient();
            Battery         = new Battery(this);
            NoiseControl    = new NoiseControl(this);
            ConcertHall     = new ConcertHallControl(this);

            _waitingList = new Semaphore(1, 1);
        }
コード例 #29
0
ファイル: Documentation.cs プロジェクト: jehy/32feet.NET
        static bool FilterDevice(BluetoothDeviceInfo dev)
        {
            var ret  = true;
            var rslt = MessageBox.Show("Include this device " + dev.DeviceAddress + " " + dev.DeviceName, "FilterDevice",
                                       MessageBoxButtons.YesNo);

            ret = rslt == DialogResult.Yes;
            Debug.Assert(rslt == DialogResult.Yes || rslt == DialogResult.No);
            return(ret);
        }
コード例 #30
0
 public RawInertialSensorProducer(BluetoothDeviceInfo btinfo)
 {
     BTClient.Connect(new InTheHand.Net.BluetoothEndPoint(btinfo.DeviceAddress, BluetoothService.SerialPort));
     //BTInfo = btinfo;
     this.DeviceAddress = btinfo.DeviceAddress.ToString();
     this.DeviceName    = btinfo.DeviceAddress.ToString();
     BTStream           = new BufferedStream(BTClient.GetStream());
     WorkerFunction     = new ThreadStart(this.StartForWorkerThread);
     WorkerThread       = new Thread(WorkerFunction);
 }
コード例 #31
0
        private bool IsConnectToDistanceDevice(BluetoothDeviceInfo bluetoothDevice)
        {
            if (bluetoothDevice != null && bluetoothDevice.Authenticated)
            {
                return(true);
            }

            ViewModel.BluetoothDeviceInfo = null;
            return(false);
        }
コード例 #32
0
        static void Main(string[] args)
        {
            BluetoothClient client = new BluetoothClient();

            BluetoothDeviceInfo scale = client.DiscoverDevices().FirstOrDefault(x => x.DeviceName.StartsWith("JD"));

            if (scale == null)
            {
                Console.WriteLine("找不到JD开头的蓝牙设备!");
                Console.ReadKey();
                return;
            }

            try
            {
                client.Connect(scale.DeviceAddress, BluetoothService.SerialPort);
                Console.WriteLine("已连接");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadKey();
            }
            NetworkStream stream = client.GetStream();
            string        weight = "";

            Console.WriteLine($"client.Connected={client.Connected}");
            Console.WriteLine($"stream != null={stream != null}");
            Console.WriteLine($"stream.DataAvailable={stream.DataAvailable}");
            //while (client.Connected
            //    && stream != null
            //    && stream.DataAvailable)
            for (int readCount = 0; readCount < 200; readCount++)//最多读200次重量
            {
                while (stream.ReadByte() != 61)
                {
                    ;                            //skip until ascii =
                }
                byte[] bytes = new byte[4];
                for (int i = 0; i < 4; i++)
                {
                    int b = client.GetStream().ReadByte();
                    //Console.WriteLine(b);
                    bytes[i] = (byte)b;
                }

                string newWeight = String.Join("", bytes.Reverse().Select(x => (char)x).ToArray());
                if (newWeight != weight)
                {
                    weight = newWeight;
                    Console.Write($"{weight}\t");
                }
            }
            Console.WriteLine("end of main!");
        }
コード例 #33
0
        public void Discover(Func <BluetoothDeviceInfo, Task> discoveryHandler, CancellationToken cancellationToken = default)
        {
            BluetoothLEAdvertisementWatcher watcher = new BluetoothLEAdvertisementWatcher();

            watcher.ScanningMode = BluetoothLEScanningMode.Active;

            watcher.Received += ReceivedHandler;

            cancellationToken.Register(() =>
            {
                watcher.Stop();
                watcher.Received -= ReceivedHandler;
            });

            watcher.Start();

            async void ReceivedHandler(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs eventArgs)
            {
                var info = new BluetoothDeviceInfo();

                if (eventArgs.Advertisement.ManufacturerData.Count > 0)
                {
                    var companyId = eventArgs.Advertisement.ManufacturerData[0].CompanyId;

                    if (companyId != LegoCompanyId && companyId != OzobotCompanyId)
                    {
                        return;
                    }

                    var reader = DataReader.FromBuffer(eventArgs.Advertisement.ManufacturerData[0].Data);
                    var data   = new byte[reader.UnconsumedBufferLength];
                    reader.ReadBytes(data);

                    info.ManufacturerData = data;

                    using (var device = BluetoothLEDevice.FromBluetoothAddressAsync(eventArgs.BluetoothAddress).AsTask().Result)
                    {
                        if (device == null)
                        {
                            return;
                        }

                        info.Name = device.Name;
                    }
                }
                else
                {
                    return;
                }

                info.BluetoothAddress = eventArgs.BluetoothAddress;

                await discoveryHandler(info);
            }
        }
コード例 #34
0
        public void Connect(BluetoothDeviceInfo device)
        {
            localClient.SetPin(null);
            localClient.BeginConnect(device.DeviceAddress, BluetoothService.SerialPort, new AsyncCallback(Connect), device);
            BluetoothEndPoint remoteEP = new BluetoothEndPoint(device.DeviceAddress, BluetoothService.SerialPort);
            BluetoothClient   client   = new BluetoothClient();

            client.Connect(remoteEP);
            localClient.Connect(remoteEP);
            this.Stream = localClient.GetStream();
        }
コード例 #35
0
 public Device(BluetoothDeviceInfo device_info)
 {
     this.Authenticated = device_info.Authenticated;
     this.Connected = device_info.Connected;
     this.DeviceName = device_info.DeviceName;
     this.LastSeen = device_info.LastSeen;
     this.LastUsed = device_info.LastUsed;
     this.Nap = device_info.DeviceAddress.Nap;
     this.Sap = device_info.DeviceAddress.Sap;
     this.Remembered = device_info.Remembered;
 }
コード例 #36
0
 public Device(BluetoothDeviceInfo device_info)
 {
     this.Authenticated = device_info.Authenticated;
     this.Connected     = device_info.Connected;
     this.DeviceName    = device_info.DeviceName;
     this.LastSeen      = device_info.LastSeen;
     this.LastUsed      = device_info.LastUsed;
     this.Nap           = device_info.DeviceAddress.Nap;
     this.Sap           = device_info.DeviceAddress.Sap;
     this.Remembered    = device_info.Remembered;
 }
コード例 #37
0
        private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            string MAC;

            foreach (BluetoothDeviceInfo dev in listBox2.SelectedItems)
            {
                MAC         = dev.DeviceAddress.ToString();
                label2.Text = MAC;
                devChosen   = dev;
            }
        }
コード例 #38
0
ファイル: Device.cs プロジェクト: kakkr1/ProjectOneLan
 /// <summary>
 /// Initializes a new instance of the <see cref="Device"/> class.
 /// </summary>
 /// <param name="device_info">
 /// The device_info.
 /// </param>
 public Device(BluetoothDeviceInfo device_info)
 {
     if (device_info != null)
     {
         DeviceInfo = device_info;
         IsAuthenticated = device_info.Authenticated;
         IsConnected = device_info.Connected;
         DeviceName = device_info.DeviceName;
         LastSeen = device_info.LastSeen;
         LastUsed = device_info.LastUsed;
         Nap = device_info.DeviceAddress.Nap;
         Sap = device_info.DeviceAddress.Sap;
         Remembered = device_info.Remembered;
     }
 }
コード例 #39
0
ファイル: Device.cs プロジェクト: sumeetjauhar/YQ
        /* These properties are not needed . They may be enabled later if needed . 
        public bool Authenticated { get; set; }
        public bool Connected { get; set; }
        public ushort Nap { get; set; }
        public uint Sap { get; set; }
        public DateTime LastSeen { get; set; }
        public DateTime LastUsed { get; set; }
        public bool Remembered { get; set; }
         */

        public Device(BluetoothDeviceInfo device_info)
        {

            this.DeviceName = device_info.DeviceName;
            this.DeviceAddress = device_info.DeviceAddress;

            /* These properties are not needed . They may be enabled later if needed . 
            this.Authenticated = device_info.Authenticated;
            this.Connected = device_info.Connected;
            this.LastSeen = device_info.LastSeen;
            this.LastUsed = device_info.LastUsed;
            this.Nap = device_info.DeviceAddress.Nap;
            this.Sap = device_info.DeviceAddress.Sap;
            this.Remembered = device_info.Remembered;
             */
        }
コード例 #40
0
ファイル: BluetoothHelper.cs プロジェクト: RoboLOGO/IDE
 public void Connect(BluetoothDeviceInfo btDevice)
 {
     bluetoothSupport.ChangeDeviceMode("Connectable");
     BluetoothAddress btAddress = BluetoothAddress.Parse(btDevice.DeviceAddress.ToString());
     if (BluetoothSecurity.PairRequest(btAddress, "1234"))
     {
         try
         {
             bluetoothClient.Connect(new BluetoothEndPoint(btAddress, bluetoothSupport.Service));
         }
         catch { }
     }
     else
     {
         throw new Exception(App.Current.TryFindResource("notconnect").ToString());
     }
 }
コード例 #41
0
        public WinBluetoothConnection(BluetoothClient connectionInfo) : this()
        {
            connection = connectionInfo;
            connectedDeviceInfo = new BluetoothDeviceInfo(connection.RemoteEndPoint.Address);
            bluetoothAddress = connection.RemoteEndPoint.Address.ToInt64();

            socket = connection.Client;
            socketReciveOperation = new SocketAsyncEventArgs();
            socketReciveOperation.UserToken = socket;
            socketReciveOperation.RemoteEndPoint = socket.RemoteEndPoint;
            socketReciveOperation.Completed += new EventHandler<SocketAsyncEventArgs>(onReciveComplete);

            socketSendOperation = new SocketAsyncEventArgs();
            socketSendOperation.UserToken = socket;
            socketSendOperation.RemoteEndPoint = socket.RemoteEndPoint;
            socketSendOperation.Completed += new EventHandler<SocketAsyncEventArgs>(onSendComplete);
          //  connection.Client

        }
コード例 #42
0
ファイル: Form7.cs プロジェクト: katadam/wockets
        public Form7(BluetoothDeviceInfo wocket)
        {
            InitializeComponent();

            //Copy parameters to loacal variables
            this.wocket = wocket;
            this.Text = "Wocket (" + wocket.DeviceAddress.ToString() + ")";

            //Load the parameters saved on the bluetoothinfo device
            this.info_cmd_value_name.Text = wocket.DeviceName;
            this.info_cmd_value_mac.Text = wocket.DeviceAddress.ToString();
            this.panel_status_texbox.Text = "";

            this.panel_status.Visible = true;
            this.panel_calibration.Visible = false;

            clean_calibration_values();

            //load sensitivity values
            info_cmd_value_sensitivity.Items.Clear();
            info_cmd_value_sensitivity.Items.Add("");
            info_cmd_value_sensitivity.Items.Add("1.5 G");
            info_cmd_value_sensitivity.Items.Add("2 G");
            info_cmd_value_sensitivity.Items.Add("4 G");
            info_cmd_value_sensitivity.Items.Add("6 G");
            info_cmd_value_sensitivity.Items.Add("8 G");
            info_cmd_value_sensitivity.SelectedIndex = 0;

            //info_cmd_value_sensitivity.FlatStyle = FlatStyle.Flat;
            //info_cmd_value_sensitivity.AllowSelection = false;

            //load transmission mode values
            info_cmd_value_tr_rate.Items.Clear();
            info_cmd_value_tr_rate.Items.Add("");
            info_cmd_value_tr_rate.Items.Add("Continuous");
            info_cmd_value_tr_rate.Items.Add("Burst Mode 30 secs");
            info_cmd_value_tr_rate.Items.Add("Burst Mode 60 secs");
            info_cmd_value_tr_rate.Items.Add("Burst Mode 90 secs");
            info_cmd_value_tr_rate.Items.Add("Burst Mode 120 secs");
            info_cmd_value_tr_rate.SelectedIndex = 0;
        }
コード例 #43
0
        public void start(BluetoothDeviceInfo serverToSend)
        {
            try
            {
                if (serverToSend.Authenticated)
                {
                    bluetoothClient = new BluetoothClient();
                                bluetoothClient.Connect(serverToSend.DeviceAddress, UUID);
                    Console.WriteLine("Conexão Estabelecida!");

                                Thread thread = new Thread(new ThreadStart(threadClientBluetooth));
                                thread.Start();
                }
                else
                {
                                Console.WriteLine("Servidor Não Autenticado!");
                }
            }
            catch (Exception e)
            {
                        Console.WriteLine("Erro: " + e.ToString());
            }
        }
コード例 #44
0
ファイル: BtDiscover.cs プロジェクト: olgg/LWork-BT
        public void InitDevice()
        {
            Ready = false;
            var cli = new BluetoothClient();
            SendMessage("Поиск устройств...");
            BluetoothDeviceInfo[] devices = cli.DiscoverDevices();
            if (devices.Any())
            {
                SendMessage(string.Format("Найдено {0} bluetooth устройств:", devices.Length));
                foreach (var foundDevice in devices)
                    SendMessage(foundDevice.DeviceName);

                device = devices.FirstOrDefault(x => x.DeviceName == DeviceName);
                if (device != null)
                {
                    SendMessage("Устройство-метка есть в списке");
                    deviceGiud = device.InstalledServices.First();
                    Ready = true;
                }
            }
            else
                SendMessage("Bluetooth устройств не обнаружено.");
        }
コード例 #45
0
 internal BluetoothWin32AuthenticationEventArgs(BLUETOOTH_DEVICE_INFO device)
 {
     m_device = new BluetoothDeviceInfo(device);
 }
コード例 #46
0
        /// <summary> Connects to a serial port defined through the current settings. </summary>
        /// <returns> true if it succeeds, false if it fails. </returns>
        public bool Connect()
        {
             
            // Reconnecting to the same device seems to fail a lot of the time, so see
            // if we can remain connected
            if (_runningBluetoothDeviceInfo!=null && _runningBluetoothDeviceInfo.DeviceAddress == CurrentBluetoothDeviceInfo.DeviceAddress && _lazyReconnect) {
                CurrentBluetoothDeviceInfo = _runningBluetoothDeviceInfo;
            } else {
                _runningBluetoothDeviceInfo = CurrentBluetoothDeviceInfo;
                //BluetoothClient.Close();
            }
            // Closing serial port if it is open
            //_stream = null;

            // set pin of device to connect with            
            // check if device is paired
            //CurrentBluetoothDeviceInfo.Refresh();
            try
            {
                if (!CurrentBluetoothDeviceInfo.Authenticated)
                {
                    //Console.WriteLine("Not authenticated");
                    _showAsConnected = false;
                    return _showAsConnected;
                }

                if (BluetoothClient.Connected && !LazyReconnect)
                {
                    //Previously connected, setting up new connection"
                    BluetoothUtils.UpdateClient();
                }

                // synchronous connection method
                if (!BluetoothClient.Connected || !_lazyReconnect)
                    BluetoothClient.Connect(CurrentBluetoothDeviceInfo.DeviceAddress, BluetoothService.SerialPort);

                if (!Open())
                {
                    // Desperate attempt: try full reset and open
                    _showAsConnected = UpdateConnectOpen();
                    return _showAsConnected;
                }

                // Check worker is not running as a precaution. This needs to be rechecked.
                if (!_worker.IsRunning) _worker.Start();

                _showAsConnected = true;
                return _showAsConnected;
            }
            catch (SocketException)
            {
                return false;
            }
            catch (InvalidOperationException)
            {
                // Desperate attempt: try full reset and open
                _showAsConnected = UpdateConnectOpen();
                return _showAsConnected;
            }
        }
コード例 #47
0
 private void escaneo()
 {
     Debug.WriteLine("Inicio de escaneo");
      BluetoothClient cliente = new BluetoothClient();
      BluetoothDeviceInfo[] dispositivos = cliente.DiscoverDevicesInRange();
      Debug.WriteLine("\n"+dispositivos.Length.ToString() + " numero de dispositivos");
      foreach (BluetoothDeviceInfo blue in dispositivos)
      {
          Debug.WriteLine(blue.DeviceAddress + " " + blue.DeviceName);
          if (blue.DeviceAddress.ToString().Equals("0015FFF21179"))
          {
              Debug.WriteLine("tenemos un ganador!! " + blue.DeviceAddress.ToString());
              dispositivomeromero = blue;
          }
      }
     //201308021034
     if (parear()){
         Debug.WriteLine("Conectado!!");
         Thread tredi = new Thread(new ThreadStart(conectio));
         tredi.Start();
     }
 }
コード例 #48
0
ファイル: MainForm.cs プロジェクト: iboxpro/windows.sdk
        private void MainForm_Load(object sender, EventArgs e)
        {
            new Thread(() =>
            {
                try
                {
                    cmb_Paired.Invoke((MethodInvoker)delegate
                    {
                        cmb_Paired.Items.Clear();
                        cmb_Paired.Enabled = false;
                        cmb_Paired.Text = "Loading paired devices...";
                    });

                    ManagementObjectSearcher ManObjSearch = new ManagementObjectSearcher("Select * from Win32_SerialPort where PNPDeviceID like 'BTHENUM%'");
                    ManagementObjectCollection ManObjReturn = ManObjSearch.Get();

                    foreach (ManagementObject ManObj in ManObjReturn)
                    {
                        string portName = ManObj["DeviceID"].ToString();
                        string pnpDeviceID = ManObj["PNPDeviceID"].ToString();

                        Console.WriteLine(portName + " " + pnpDeviceID);

                        string macAddress;

                        try
                        {
                            int startIndex = pnpDeviceID.LastIndexOf('&') + 1;
                            int endIndex = pnpDeviceID.LastIndexOf('_');
                            macAddress = pnpDeviceID.Substring(startIndex, endIndex - startIndex);
                        }
                        catch
                        {
                            continue;
                        }

                        if (macAddress == "000000000000")
                        {
                            continue;
                        }

                        BluetoothAddress bluetoothAddress = BluetoothAddress.CreateFromBigEndian(hexToByteArray(macAddress));
                        BluetoothDeviceInfo bluetoothDeviceInfo = new BluetoothDeviceInfo(bluetoothAddress);
                        string deviceName = bluetoothDeviceInfo.DeviceName;

                        portInfos.Add(new PortInfo(portName, deviceName));
                        cmb_Paired.Invoke((MethodInvoker)delegate { cmb_Paired.Items.Add(deviceName); });
                    }

                    if (cmb_Paired.Items.Count == 0)
                    {
                        string[] ports = SerialPort.GetPortNames();
                        for (int i = 0; i < ports.Length; ++i)
                        {
                            portInfos.Add(new PortInfo(ports[i], ""));
                            cmb_Paired.Invoke((MethodInvoker)delegate { cmb_Paired.Items.Add(ports[i]); });
                        }
                    }

                    cmb_Paired.Invoke((MethodInvoker)delegate
                    {
                        if (cmb_Paired.Items.Count == 0)
                        {
                            cmb_Paired.Text = "Device not found";
                        }
                        else
                        {
                            cmb_Paired.Text = "";
                            cmb_Paired.Enabled = true;
                        }
                    });
                }
                catch { }
            }).Start();
        }
コード例 #49
0
ファイル: BTUtils.cs プロジェクト: ArmyOfPirates/PS3BluMote
        public static RemoteBtStates RemoteBtState(string btAddress, BluetoothDeviceInfo dev)
        {
            RemoteBtStates result = RemoteBtStates.Unknown;
            BluetoothDeviceInfo device = null;
            if (dev == null && btAddress == null) return result;
            else if (dev == null)
            {
                try { device = new BluetoothDeviceInfo(BluetoothAddress.Parse(btAddress)); }
                catch
                {
                    DebugLog.write("BTUtils.RemoteBtState failed while creating BluetoothDeviceInfo");
                }
            }
            else device = dev;

            if (device != null)
            {
                try
                {
                    ServiceRecord[] services = device.GetServiceRecords(BluetoothService.HumanInterfaceDevice);
                    result = RemoteBtStates.Awake;
                }
                catch
                {
                    result = RemoteBtStates.Hibernated;
                }
            }
            if (result == RemoteBtStates.Unknown) DebugLog.write("BTUtils.RemoteBtState returns Unknown");
            else if (result == RemoteBtStates.Awake) DebugLog.write("BTUtils.RemoteBtState returns Awake");
            else if (result == RemoteBtStates.Hibernated) DebugLog.write("BTUtils.RemoteBtState returns Hibernated");
            return result;
        }
コード例 #50
0
ファイル: BTUtils.cs プロジェクト: ArmyOfPirates/PS3BluMote
        public static void SetHIDServiceState(bool state, string btAddress, BluetoothDeviceInfo dev)
        {
            try
            {
                BluetoothDeviceInfo device;
                if (dev == null && btAddress == null) return;
                else if (dev == null) device = new BluetoothDeviceInfo(BluetoothAddress.Parse(btAddress));
                else device = dev;

                if (state) DebugLog.write("Reconnecting HID Service from the Remote...");
                else DebugLog.write("Disconnecting HID Service from the Remote...");

                device.SetServiceState(BluetoothService.HumanInterfaceDevice, state);

                if (state) DebugLog.write("HID Service reconnected...");
                else DebugLog.write("HID Service disconnected...");
            }
            catch
            {
                DebugLog.write("BTUtils.SetHIDServiceState failed");
            }
        }
コード例 #51
0
        public static void PrintDevice(BluetoothDeviceInfo device)
        {
            // log and save all found devices

            Console.Write(device.DeviceName + " (" + device.DeviceAddress + "): Device is ");
            Console.Write(device.Remembered ? "remembered" : "not remembered");
            Console.Write(device.Authenticated ? ", paired" : ", not paired");
            Console.WriteLine(device.Connected ? ", connected" : ", not connected");
        }
コード例 #52
0
        public static void ConnectDevice(BluetoothDeviceInfo device, string devicePin)
        {
            // set pin of device to connect with
            if (devicePin != null) LocalClient.SetPin(devicePin);

            // check if device is paired
            if (device.Authenticated)
            {
                // synchronous connection method
                LocalClient.Connect(device.DeviceAddress, BluetoothService.SerialPort);
                if (LocalClient.Connected)
                {
                    _stream = LocalClient.GetStream();
                    _stream.ReadTimeout = 500;
                }                
            }            
        }
コード例 #53
0
        public static bool PairDevice(BluetoothDeviceInfo device)
        {
            if (device.Authenticated) return true;
            // loop through common PIN numbers to see if they pair
            foreach (var devicePin in CommonDevicePins)
            {
                var isPaired = BluetoothSecurity.PairRequest(device.DeviceAddress, devicePin);
                if (isPaired) break;
            }

            device.Update();
            return device.Authenticated;
        }
コード例 #54
0
 public static extern int BluetoothGetDeviceInfo(IntPtr hRadio, ref BluetoothDeviceInfo pbtdi);
コード例 #55
0
 /*
  * Default constructor used for iOS
  */
 public SpheroIOS()
     : base()
 {
     m_DeviceInfo = new BluetoothDeviceInfo("", "");
 }
コード例 #56
0
ファイル: AvailableSphero.cs プロジェクト: slodge/BallControl
 public AvailableSphero(BluetoothDeviceInfo peerInformation)
     : base(peerInformation)
 {
 }
コード例 #57
0
 internal BluetoothWin32AuthenticationEventArgs(int errorCode, BluetoothWin32AuthenticationEventArgs previousEa)
 {
     if (previousEa == null) {
         throw new ArgumentNullException("previousEa");
     }
     m_device = previousEa.Device;
     m_attemptNumber = previousEa.AttemptNumber + 1;
     //
     m_errorCode = errorCode;
 }
コード例 #58
0
	/* More detailed constructor used for Android */ 
	public SpheroAndroid(AndroidJavaObject sphero, string bt_name, string bt_address) : base() {		
		m_AndroidJavaSphero = sphero;
		m_DeviceInfo = new BluetoothDeviceInfo(bt_name, bt_address);
	}
コード例 #59
-1
 /// <summary>
 /// Constructor, tries to connect 3x to NXT then fails
 /// </summary>
 /// <param name="nxtName">NXT brick name, case sensitive</param>
 /// <param name="connectionTries">Max failed try to connect</param>
 public NXTBluetooth(string nxtName, int connectionTries = 3)
 {
     _maxTries = connectionTries;
        try {
             _btc = new BluetoothClient(); // instantiate bluetooth connection
             debugMessage(@"Bluetooth is discovering devices");
             _bdi = _btc.DiscoverDevices(); // get all bluetooth devices
     #if DEBUG
             debugMessage(@"Bluetooth devices:");
             foreach (BluetoothDeviceInfo info in _bdi) {
                  Console.WriteLine(info.DeviceName);
             }
     #endif
             // linq to match our NXT name
             var nxt = from n in this._bdi where n.DeviceName == nxtName select n;
             if (nxt != null && nxt.Count<BluetoothDeviceInfo>() > 0) {
                  // get the NXT device info
                  _nxt = (BluetoothDeviceInfo)nxt.First<BluetoothDeviceInfo>();
             } else {
                  // no NXT of that name exists
                  throw new Exception("Cannot find NXT name from Bluetooth device list");
             }
             debugMessage(@"Bluetooth Initialized, NXT found");
        } catch (Exception) {
             throw;
        }
        _client = null;
        int tries = 1;
        do {
             debugMessage(string.Format(@"Connecting to NXT... on {0} try...", tries));
             try {
                  // now if we have found our NXT
                  _client = new BluetoothClient();
                  // we will connect to the NXT using the device info we got earlier
                  _client.Connect(_nxt.DeviceAddress, _SERVICENAME);
             } catch (SocketException se) {
                  if ((tries >= this._maxTries)) {
                       // gave up trying to connect
                       throw se;
                  }
                  debugMessage(string.Format(@"Error establishing contact, retrying {0} time", tries));
                  _client = null;
             }
             // if we cant connect, we can try and try, default is 3 times
             tries = tries + 1;
        } while (_client == null & tries <= this._maxTries);
        // after these, if client is not null then we are connected! we can use _client now
        if ((_client == null)) {
             //timeout occurred
             debugMessage(@"Error establishing contact, fail");
             throw new Exception(@"Cannot connect to NXT... Terminating...");
        }
        debugMessage(@"Connected to NXT...");
 }
コード例 #60
-1
ファイル: Bluetooth.cs プロジェクト: smo-key/NXTLib
        /// <summary> 
        /// Connect to the device via Bluetooth.
        /// </summary>
        public override void Connect(Brick brick)
        {
            Initialize();
            if (!IsConnected)
            {
                lock (commLock)
                {
                    BluetoothAddress adr = new BluetoothAddress(brick.brickinfo.address);
                    BluetoothDeviceInfo device = new BluetoothDeviceInfo(adr);
                    BluetoothSecurity.PairRequest(adr, "1234");

                    client.Connect(adr, NXT_GUID);

                    //BluetoothSecurity.RevokePin(adr);
                    //BluetoothSecurity.RemoveDevice(adr);

                }
                if (!IsConnected) { throw new NXTNotConnected(); }
            }
            return;
        }