当前位置: 首页>>代码示例>>C#>>正文


C# BluetoothClient.Close方法代码示例

本文整理汇总了C#中InTheHand.Net.Sockets.BluetoothClient.Close方法的典型用法代码示例。如果您正苦于以下问题:C# BluetoothClient.Close方法的具体用法?C# BluetoothClient.Close怎么用?C# BluetoothClient.Close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在InTheHand.Net.Sockets.BluetoothClient的用法示例。


在下文中一共展示了BluetoothClient.Close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: MakeConnection

        public static void MakeConnection(BluetoothAddress btAddress)
        {
            var serviceClass = BluetoothService.SerialPort;
            if (_cli != null)
            {
                _cli.Close();
            }

            _cli = new BluetoothClient();
            var bluetoothDeviceInfos = _cli.DiscoverDevices();
            var deviceInfos = bluetoothDeviceInfos.ToList();
            BluetoothDeviceInfo device = null;
            foreach (var bluetoothDeviceInfo in deviceInfos)
            {
                var scannedDeviceAddress = bluetoothDeviceInfo.DeviceAddress;

                if (scannedDeviceAddress == btAddress)
                {
                    device = bluetoothDeviceInfo;
                }
            }

            if (device == null)
            {
                return;
            }

            var ep = new BluetoothEndPoint(device.DeviceAddress, serviceClass);

            try
            {
                if (!device.Connected)
                {
                    _cli.Connect(ep);
                }
            }
            catch(System.Net.Sockets.SocketException e)
            {
                _cli.Close();
                _isConnected = false;
                return;
            }

            _isConnected = true;
        }
开发者ID:idan573,项目名称:projectArduinoFirstTry,代码行数:45,代码来源:BluetoothHandler.cs

示例2: search

        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;
                        }
                    }
//.........这里部分代码省略.........
开发者ID:smackay,项目名称:Open-Source-Automation,代码行数:101,代码来源:Bluetooth.cs

示例3: BluetoothConnect

        void BluetoothConnect()
        {
            string androidTabletMAC = "68:05:71:AA:2B:C7"; // The MAC address of my phone, lets assume we know it

            BluetoothAddress addr = BluetoothAddress.Parse(androidTabletMAC);
            //var btEndpoint = new BluetoothEndPoint(addr, 1600);
            var btClient = new BluetoothClient();
            //btClient.Connect(btEndpoint);

            Stream peerStream = btClient.GetStream();

            StreamWriter sw = new StreamWriter(peerStream);
            sw.WriteLine("Hello World");
            sw.Flush();
            sw.Close();

            btClient.Close();
            btClient.Dispose();
               // btEndpoint = null;
        }
开发者ID:AstaraelWeeper,项目名称:MainServerPlayer,代码行数:20,代码来源:Bluetooth.cs

示例4: button1_Click

        private void button1_Click(object sender, EventArgs e)
        {
            this.listBox1.Items.Clear();
            this.label2.Text = "Searching... please wait";
            this.label2.Update();
            try
            {
                BluetoothRadio.PrimaryRadio.Mode = RadioMode.Connectable;
                BluetoothClient btc = new BluetoothClient();

                devices = btc.DiscoverDevices(60, false, true, true);

                for (int i = 0; (i < devices.Length); i++)
                {
                    //if the device is a wocket
                    if (((devices[i].DeviceName.IndexOf("Wocket") >= 0)
                        || (devices[i].DeviceName.IndexOf("WKT") >= 0)
                        || (devices[i].DeviceName.IndexOf("FireFly") >= 0)
                        || (devices[i].DeviceName.IndexOf("0006660") >= 0)
                        && (wocketCount < 100)))
                    {
                        string hex = "";
                        hex = devices[i].DeviceAddress.ToString();

                        #region Commented
                        // if (this.WocketsList_Box.Items.IndexOf(hex) < 0)
                        //{
                        //    this.WocketsList_Box.Items.Add(devices[i].DeviceName + " (" + hex + ")");
                        //macaddresses.Add(hex);
                        //}
                        #endregion Commented

                        this.listBox1.Items.Add(hex);
                        bluetoothlist.Add(hex, devices[i]);

                        wocketCount++;
                    }
                }

                btc.Dispose();
                btc.Close();
            }
            catch
            {
                MessageBox.Show("Cannot connect: please check your Bluetooth radio is plugged in and active");
                Environment.Exit(0);
            }
        }
开发者ID:katadam,项目名称:wockets,代码行数:48,代码来源:Form1.cs

示例5: receive_file

        public override void receive_file(String devicename, String bluid, int not)
        {
            try
            {
                _stopwatch.Start();
                scan_transfer_speed();                

                _bluetooth_guid = Guid.Parse(bluid);
                _bluetooth_listener = new BluetoothListener(_bluetooth_guid);
                _bluetooth_listener.Start();

                _bluetooth_client = _bluetooth_listener.AcceptBluetoothClient();
                _netstream = _bluetooth_client.GetStream();

                _filestream = new FileStream(this.filepath, FileMode.Create, FileAccess.ReadWrite);

                int length;
                _buffer = new byte[65000];
                
                while ((length = _netstream.Read(_buffer, 0, _buffer.Length)) != 0)
                {
                    while (_writing) { }

                    _count_received_bytes += length;

                    _filestream.Write(_buffer, 0, length);
                }

                _timer_ts.Close();
                _stopwatch.Stop();

                int _transferspeed = _count_received_bytes / 1024;
                _message = format_message(_stopwatch.Elapsed, "Transferspeed", _transferspeed.ToString(), "kB/s");
                this.callback.on_transfer_speed_change(_message, this.results);
                this.main_view.text_to_logs(_message);

                _filestream.Dispose();
                _filestream.Close();

                _netstream.Dispose();
                _netstream.Close();

                _bluetooth_client.Dispose();
                _bluetooth_client.Close();

                _bluetooth_listener.Stop();

                _message = format_message(_stopwatch.Elapsed, "File Transfer", "OK", this.filepath);
                this.callback.on_file_received(_message, this.results);
                this.main_view.text_to_logs(_message);
            }
            catch (Exception e)
            {
                append_error_tolog(e, _stopwatch.Elapsed, devicename);
            }
        }               
开发者ID:StabilityofWT,项目名称:Stability-Monitor,代码行数:56,代码来源:Bluetooth_agent.cs

示例6: sendMessage

 private void sendMessage(int NumRetries, byte[] Buffer, int BufferLen) {
     BluetoothClient client = null;
     int CurrentTries = 0;
     for (
     ; ((client == null) 
                 && (CurrentTries < NumRetries)); 
     ) {
         try {
             client = new BluetoothClient();
             client.Connect(new BluetoothEndPoint(((BluetoothDeviceInfo)(cboDevices.SelectedItem)).DeviceAddress, ServiceName));
         }
         catch (SocketException se) {
             if ((CurrentTries >= NumRetries)) {
                 throw se;
             }
             client = null;
         }
         CurrentTries = (CurrentTries + 1);
     }
     if ((client == null)) {
         // timeout occurred
         MsgBox("Error establishing contact");
         return;
     }
     System.IO.Stream stream = null;
     try {
         stream = client.GetStream();
         stream.Write(Buffer, 0, BufferLen);
     }
     catch (Exception e) {
         MsgBox("Error sending");
     }
     finally {
         if (!(stream == null)) {
             stream.Close();
         }
         if (!(client == null)) {
             client.Close();
         }
     }
 }
开发者ID:andrejpanic,项目名称:win-mobile-code,代码行数:41,代码来源:ChatForm.cs

示例7: ClientConnected

        internal void ClientConnected(BluetoothClient client)
        {
            Stream stream = null;
            try
            {
                Log.BtServer("MScanner med navn " + client.RemoteMachineName + " kobler til..");
                this.clientName = client.RemoteMachineName;
                this.clientAccepted = false;
                this.clientAppName = "Unknown";
                this.clientAppVersion = 0;
                stream = client.GetStream();
                stream.ReadTimeout = 10 * 1000;

                if (main.appConfig.blueServerDatabaseUpdated.Date != DateTime.Now.Date)
                {
                    Log.BtServer("App-databasene trenger oppdatering. Sist oppdatert: " + main.appConfig.blueServerDatabaseUpdated.ToShortDateString());
                    if (FormMain.appManagerIsBusy)
                        Log.BtServer("AppManager er opptatt: App-databasene er iferd med å bli oppdatert");
                    else
                    {
                        AppManager app = new AppManager(main);
                        app.UpdateAllAsync();
                        return;
                    }
                }

                while (true)
                {
                    try
                    {
                        if (!client.Connected || !serverStarted)
                            break;

                        if (!clientAccepted) // Client is not initialized, run init routine..
                            this.clientAccepted = serverInitConnectionRoutine(stream);

                        string strServerMsg = waitForMessage(stream);
                        if (strServerMsg.StartsWith(CMD_UPDATE_PRODUCT))
                        {
                            if (!serverUpdateRoutine(stream, strServerMsg, dataFilename))
                                break;
                        }
                        if (strServerMsg.StartsWith(CMD_UPDATE_INVENTORY))
                        {
                            if (!serverUpdateRoutine(stream, strServerMsg, inventoryFilename))
                                break;
                        }
                        if (strServerMsg.StartsWith(CMD_GOODBYE))
                        {
                            Log.BtServer("(" + this.clientName + ") Goodbye!");
                            break;
                        }

                        Thread.Sleep(300); // Used to limit the number of loops per second
                    }
                    catch (Exception ex)
                    {
                        Log.BtServer("Kommunikasjons feil med " + this.clientName + ". Kobler fra..", true);
                        Log.Unhandled(ex);
                        break;
                    }
                }

                if (stream != null)
                {
                    stream.Flush();
                    stream.Close();
                }

                if (client != null)
                    client.Close();

                Log.BtServer("(" + this.clientName + ") Koblet fra.");
            }
            catch (Exception ex)
            {
                Log.BtServer("Generell feil: " + ex.Message);
            }
            finally
            {
                if (stream != null)
                {
                    stream.Flush();
                    stream.Close();
                    stream = null;
                }
                if (client != null)
                {
                    client.Close();
                    client = null;
                }
            }
        }
开发者ID:tborgund,项目名称:kgsa,代码行数:93,代码来源:BluetoothServer.cs

示例8: SendZip


//.........这里部分代码省略.........
                                {
                                    this.Status = "Too big file!";
                                    MessageBox.Show("Too big file!");
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.LogEvent(true, "MainViewModel.SendZip 207 Exception = {0} , \nStack = {1}", ex.Message, ex.StackTrace);
                            lastEx = ex;
                        }
                        finally
                        {
                            //if (bluetoothClient != null)
                            //{
                            //    //bluetoothStream.Flush();
                            //    //bluetoothStream.Close();

                            //    bluetoothClient.Close();
                            //    bluetoothClient.Dispose();
                            //}
                        }
                    }

                    Logger.LogEvent(true, "MainViewModel.SendZip 208");

                    this.StopTimer(aTimer);
                    //if (bluetoothStream != null)
                    //{
                    //    bluetoothStream.Flush();
                    //    bluetoothStream.Close();
                    //}

                    if (bluetoothClient != null)
                    {
                        Logger.LogEvent(true, "MainViewModel.SendZip 209");

                        bluetoothClient.Close();
                        bluetoothClient.Dispose();
                        bluetoothClient = null;
                    }

                    Logger.LogEvent(true, "MainViewModel.SendZip 210");
                }
            }).ContinueWith(taskState =>
            {
                Logger.LogEvent(true, "MainViewModel.SendZip 211");

                this.IsScanning = false;

                if (success)
                {
                    this.Status = string.Format("File \"{0}\" has been transferred to {1}!", Path.GetFileNameWithoutExtension(this.lastZipPath) + ".lmu", this.selectedDevice.Name);
                    this.ClearAfterSendOrCancel();
                }
                else if (!this.wasCanceled)
                {
                    this.Status = "Form transfering failed.";

                    Logger.LogEvent(true, "MainViewModel.SendZip 212 lastEx: {0}", lastEx == null ? "IsNULL" : "Not NULL");

                    if (lastEx != null)
                    {
                        if (lastEx is SocketException)
                        {
                            var socketEx = (SocketException)lastEx;

                            BluetoothRadio.PrimaryRadio.Mode = RadioMode.PowerOff;

                            if (socketEx.SocketErrorCode == SocketError.AddressNotAvailable || socketEx.SocketErrorCode == SocketError.TimedOut)
                            {
                                MessageBox.Show("Selected bluetooth device is not available. Please press \"App Update\" button on an appropriate device before sending forms.", "Destination device is not reachable.",
                                    MessageBoxButton.OK, MessageBoxImage.Warning);
                            }
                            else if (socketEx.SocketErrorCode == SocketError.InvalidArgument || socketEx.SocketErrorCode == SocketError.Shutdown)
                            {
                                MessageBox.Show("Try one of next solutions:\n- Try to restart the application\n- Unpair devices in settings (for both devices) and pair them again.\n",
                                    "Bluetooth connection problem.", MessageBoxButton.OK, MessageBoxImage.Error);
                            }
                            else// if (lastEx.Message.Contains("invalid argument was supplied")) // (lastEx as SocketException).SocketErrorCode == SocketError.Shutdown
                            {
                                MessageBox.Show("Try one of next solutions:\n- Try to restart the application;\n- Unpair devices in settings (for both devices) and pair them again;\n- Go to Start > Type services.msc > Services Local > Then scroll down the list till you see 'Bluetooth Support Service' > Right click on it and then Stop the process and then start it up again;\n- Update bluetooth drivers;",
                                    "Bluetooth connection problem.", MessageBoxButton.OK, MessageBoxImage.Error);
                            }
                        }

                        Logger.LogEvent(true, "MainViewModel.SendZip 213");

                        this.AddExceptionToLog(lastEx);
                    }

                    this.SelectedDeviceIndex = -1;
                }

                Logger.LogEvent(true, "MainViewModel.SendZip 214");

            }, TaskScheduler.FromCurrentSynchronizationContext());

            Logger.LogEvent(true, "MainViewModel.SendZip 215");
        }
开发者ID:Last-Mile-Health,项目名称:ODK-Liberia-LaptopTransfer,代码行数:101,代码来源:MainViewModel.cs

示例9: ConnectSocket

        /// <summary>
        /// If we were not provided with a btClient on creation we need to create one
        /// </summary>
        private void ConnectSocket()
        {
            try
            {
                if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Trace("Connecting bluetooth client with " + ConnectionInfo);

                bool connectSuccess = true;

                //We now connect to our target
                btClient = new BluetoothClient();

                //Start the connection using the async version
                //This allows us to choose our own connection establish timeout
                IAsyncResult ar = btClient.BeginConnect((ConnectionInfo.RemoteEndPoint as BluetoothEndPoint), null, null);
                WaitHandle connectionWait = ar.AsyncWaitHandle;
                try
                {
                    if (!ar.AsyncWaitHandle.WaitOne(NetworkComms.ConnectionEstablishTimeoutMS, false))
                    {
                        btClient.Close();
                        connectSuccess = false;
                    }

                    btClient.EndConnect(ar);
                }
                finally
                {
                    connectionWait.Close();
                }

                if (!connectSuccess) throw new ConnectionSetupException("Timeout waiting for remoteEndPoint to accept bluetooth connection.");
            }
            catch (Exception ex)
            {
                CloseConnection(true, 17);
                throw new ConnectionSetupException("Error during bluetooth connection establish with destination (" + ConnectionInfo + "). Destination may not be listening or connect timed out. " + ex.ToString());
            }
        }
开发者ID:MarcFletcher,项目名称:NetworkComms.Net,代码行数:41,代码来源:BluetoothConnection.cs

示例10: Open

        public void Open(String url)
        {
            try{

            var parsed_url = ParseUrl(url);
            Logger.trace("BluetoothStream", "Open " + parsed_url[URL_ADDR] + " serviceid " + parsed_url[URL_SVC] + " pin " + parsed_url[URL_PIN]);

            try{
                BluetoothRadio.PrimaryRadio.Mode = RadioMode.Discoverable;
            }catch(Exception e){
                Logger.error("BluetoothStream", "set_Mode", e);
            }

            BluetoothAddress address = BluetoothAddress.Parse(parsed_url[URL_ADDR]);

            bluetoothClient = new BluetoothClient();

            try{
                if (parsed_url[URL_PIN] != null)
                {
                    bluetoothClient.SetPin(address, parsed_url[URL_PIN]);
                }
            }catch(Exception){
                Logger.error("BluetoothStream", "SetPin");
            }

            #if xxBLUETOOTH_USE_PAIRREQUEST
            // advice from some user - but was useless. other user reported "unable to connecte because of this"
            if (parsed_url[URL_PIN] != null)
            try{
                for(var i = 0; i < 3; i++){
                    var res = BluetoothSecurity.PairRequest(address, parsed_url[URL_PIN]);
                    if (res)
                        break;
                    Logger.error("BluetoothStream", "PairRequest failed, retry "+i);
                }
            }catch(Exception){
                Logger.error("BluetoothStream", "PairRequest");
            }
            #endif

            BluetoothEndPoint btep;

            // force serviceid for some popular china BT adapters
            if (parsed_url[URL_SVC] == null && try_with_service) {
                parsed_url[URL_SVC] = "1";
            }

            if (parsed_url[URL_SVC] != null)
                btep = new BluetoothEndPoint(address, BluetoothService.SerialPort, int.Parse(parsed_url[URL_SVC]));
            else
                btep = new BluetoothEndPoint(address, BluetoothService.SerialPort);
            bluetoothClient.Connect(btep);
            stream = bluetoothClient.GetStream();
            if (stream == null){
                bluetoothClient.Close();
                bluetoothClient = null;
            }else{
                if (stream.CanTimeout){
                    stream.WriteTimeout = 2;
                    stream.ReadTimeout = 2;
                }
            }
            }catch(Exception e){
            if (bluetoothClient != null)
            {
                bluetoothClient.Close();
                bluetoothClient = null;
            }
            if (!try_with_service){
                try_with_service = true;
                Open(url);
                return;
            }
            throw;
            }
        }
开发者ID:cail,项目名称:hobd,代码行数:77,代码来源:BlueToothStream.cs

示例11: button_search_Click

        //Search
        private void button_search_Click(object sender, EventArgs e)
        {
            try
            {
                this.label_status.Text = "Please wait... searching for wockets";
                this.Refresh();
                this.button_search.Enabled = false;

                this.dataGridView1.Rows.Clear();
                this.macaddresses.Clear();
                bluetoothlist.Clear();
                int wocketCount = 0;

                if (BluetoothRadio.PrimaryRadio.Mode != RadioMode.Connectable)
                {
                    BluetoothRadio.PrimaryRadio.Mode = RadioMode.Connectable;
                }
                BluetoothClient btc = new BluetoothClient();

                label_status.Text = "Searching for wockets...";
                Application.DoEvents();

                devices = btc.DiscoverDevices(60, true, true, true);

                for (int i = 0; (i < devices.Length); i++)
                {
                    //if the device is a wocket
                    if (((devices[i].DeviceName.IndexOf("Wocket") >= 0)
                        || (devices[i].DeviceName.IndexOf("WKT") >= 0)
                        || (devices[i].DeviceName.IndexOf("FireFly") >= 0)
                        || (devices[i].DeviceName.IndexOf("00:06:66") >= 0)
                        && (wocketCount < 100)))
                    {
                        string hex = "";
                        hex = devices[i].DeviceAddress.ToString();

                        System.Threading.Thread.Sleep(1000);

                        if (this.macaddresses.IndexOf(hex) < 0)
                        {
                            int row = this.dataGridView1.Rows.Add();

                            this.dataGridView1.Rows[row].Cells[0].Value = devices[i].DeviceName;
                            this.dataGridView1.Rows[row].Cells[1].Value = hex;
                            this.dataGridView1.Rows[row].Cells[2].Value = "Not tested";
                            this.dataGridView1.Rows[row].Cells[3].Value = "Not tested";

                            macaddresses.Add(hex);
                            bluetoothlist.Add(devices[i]);

                            System.Threading.Thread.Sleep(1000);

                        }

                        wocketCount++;
                    }
                }

                btc.Dispose();
                btc.Close();

                if (this.dataGridView1.Rows.Count > 0)
                {
                    this.button_test.Enabled = true;
                    this.button_settings.Enabled = true;
                }

                label_status.Text = "Waiting for wocket...";

            }
            catch
            {
                label_status.Text = "BT module not responding.";
            }

            this.button_search.Enabled = true;
        }
开发者ID:katadam,项目名称:wockets,代码行数:78,代码来源:Form4.cs

示例12: DiscoverLoop

        /// <summary>
        /// Threaded loop discovers new devices in range and sends this Members profile
        /// if they have not yet received it.
        /// </summary>
		public void DiscoverLoop()
		{
            // on exit, run is set to false to terminate all threads
			while(run)
			{
                // create a new bluetooth client object
				BluetoothClient bt = new BluetoothClient();

                // return a maximum of 10 devices
				bTDevices = bt.DiscoverDevices(10);

                //close the bluetooth client object
				bt.Close();

                // loop through all the devices found
				for(int i=0;i<BTDevices.Length;i++)
				{
                    // check again if the application is exiting and terminate threads
                    // this makes the application end much faster
                    if (!run)
                    {
                        // stop the listener
                        btListener.Stop();
                        // exit the loop
                        break;
                    }

					try
					{
                        // the device isnt looing at itself
                        if (BTDevices[i].DeviceAddress.ToString() != this.MACAddress)
                        {
                            // if the device name is not in the match list
                            if (!MainForm.member.MatchExists(BTDevices[i].DeviceAddress.ToString()))
                            {   //Send profile and request that a profile not be returned by using "0" parameter
                                SendBluetoothProfile(bTDevices[i].DeviceAddress, 0);
                            }

                        }
					}
					catch(Exception e)
					{
						//throw e;
                        // an exception will be thrown if the remote device doesnt reply in time
                        // this is quite a frequent occurance due to the nature of mobile bluetooth
					}
				}
			}
		}
开发者ID:xuchuansheng,项目名称:GenXSource,代码行数:53,代码来源:BluetoothCom.cs

示例13: SerialOpen

        public void SerialOpen(String portName, BaudRates baud)
        {
            if (portName.StartsWith("COM")){
                BasicPortSettings portSettings = new BasicPortSettings();
                portSettings.BaudRate = baud;
                mPort = new Port(portName+":", portSettings);
                mPort.RThreshold = 1;
                mPort.SThreshold = 1;	// send 1 byte at a time
                mPort.InputLen = 0;
                mPort.Open();
                mPort.DataReceived +=new Port.CommEvent(mPort_DataReceived);
            }else{

                try{
                    BluetoothAddress address = BluetoothAddress.Parse(portName);
                    bluetoothClient = new BluetoothClient();
                    bluetoothClient.SetPin(address, "0000");
                    BluetoothEndPoint btep = new BluetoothEndPoint(address, BluetoothService.SerialPort, 1);
                    bluetoothClient.Connect(btep);
                    stream = bluetoothClient.GetStream();
                    if (stream == null){
                        bluetoothClient.Close();
                        bluetoothClient = null;
                    }else{
                        if (stream.CanTimeout){
                            stream.WriteTimeout = 2;
                            stream.ReadTimeout = 2;
                        }
                    }
                }catch(System.IO.IOException){
                    bluetoothClient = null;
                }

            }
        }
开发者ID:cail,项目名称:obdgauge,代码行数:35,代码来源:OBDSerial.cs

示例14: checkconnection

 public void checkconnection(BluetoothDeviceInfo dev, Guid serviceClass, BluetoothClient bc)
 {
     int attempts = 0;
     int maxTries = 2;
     while (attempts < maxTries)
     {
         try
         {
             ServiceRecord[] records = dev.GetServiceRecords(serviceClass);
             Thread.Sleep(10);
         }
         catch (SocketException exception)
         {
             var msgg = " (" + exception.ErrorCode.ToString() + ") -- ";
             //
             msgg += "Bluetooth connection No longer exists : " + exception.Message;
             log.dispatchLogMessage(msgg);
             attempts++;
             msgg = "Making attempt " + attempts + " to connect back";
             log.dispatchLogMessage(msgg);
         }
     }
     bc.Close();
 }
开发者ID:sumeetjauhar,项目名称:YQ,代码行数:24,代码来源:bluetooth_devices.xaml.cs

示例15: button_search_Click

        private void button_search_Click(object sender, EventArgs e)
        {
            this.label_status.Text = "Please wait... searching for wockets";
            this.Refresh();
            this.button_search.Enabled = false;
            this.listBox1.Items.Clear();
            BluetoothRadio.PrimaryRadio.Mode = RadioMode.Connectable;
            BluetoothClient btc = new BluetoothClient();

            devices = btc.DiscoverDevices(60, false, false, true);
            int wocketCount = 0;
            for (int i = 0; (i < devices.Length); i++)
            {
                //if the device is a wocket
                if (((devices[i].DeviceName.IndexOf("Wocket") >= 0)
                    || (devices[i].DeviceName.IndexOf("WKT") >= 0)
                    || (devices[i].DeviceName.IndexOf("FireFly") >= 0)
                    || (devices[i].DeviceName.IndexOf("00:06:66") >= 0))
                    && (wocketCount < 100))
                {
                    string hex = "";
                    hex = devices[i].DeviceAddress.ToString();
                    if (this.listBox1.Items.IndexOf(hex) < 0)
                    {
                        this.listBox1.Items.Add(devices[i].DeviceName + " (" + hex + ")");
                        macaddresses.Add(hex);
                    }
                    wocketCount++;
                }
            }
            btc.Dispose();
            btc.Close();

            if (this.listBox1.Items.Count > 0)
                this.button_configure.Enabled = true;
            this.button_search.Enabled = true;
        }
开发者ID:katadam,项目名称:wockets,代码行数:37,代码来源:Form1.cs


注:本文中的InTheHand.Net.Sockets.BluetoothClient.Close方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。