コード例 #1
1
        /// <summary>
        /// Sends the data to the Receiver.
        /// </summary>
        /// <param name="device">The device.</param>
        /// <param name="content">The content.</param>
        /// <returns>If was sent or not.</returns>
        public async Task<bool> Send(Device device, string content)
        {
            if (device == null)
            {
                throw new ArgumentNullException("device");
            }

            if (string.IsNullOrEmpty(content))
            {
                throw new ArgumentNullException("content");
            }

            // for not block the UI it will run in a different threat
            var task = Task.Run(() =>
            {
                using (var bluetoothClient = new BluetoothClient())
                {
                    try
                    {
                        var ep = new BluetoothEndPoint(device.DeviceInfo.DeviceAddress, _serviceClassId);
                       
                        // connecting
                        bluetoothClient.Connect(ep);

                        // get stream for send the data
                        var bluetoothStream = bluetoothClient.GetStream();

                        // if all is ok to send
                        if (bluetoothClient.Connected && bluetoothStream != null)
                        {
                            // write the data in the stream
                            var buffer = System.Text.Encoding.UTF8.GetBytes(content);
                            bluetoothStream.Write(buffer, 0, buffer.Length);
                            bluetoothStream.Flush();
                            bluetoothStream.Close();
                            return true;
                        }
                        return false;
                    }
                    catch
                    {
                        // the error will be ignored and the send data will report as not sent
                        // for understood the type of the error, handle the exception
                    }
                }
                return false;
            });
            return await task;
        }
コード例 #2
0
        public static void GetImages(BluetoothEndPoint endpoint, Color tagColor)
        {
            InTheHand.Net.Sockets.BluetoothClient btc = new InTheHand.Net.Sockets.BluetoothClient();
            btc.Connect(endpoint);
            var nws = btc.GetStream();

            byte[] emptySize = BitConverter.GetBytes(0); //
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(emptySize);              // redundant but usefull in case the number changes later..
            }
            nws.Write(emptySize, 0, emptySize.Length); // write image size
            int imgCount = GetImgSize(nws);

            nws = btc.GetStream();
            for (int i = 0; i < imgCount; i++)
            {
                MemoryStream ms   = new MemoryStream();
                int          size = GetImgSize(nws);
                if (size == 0)
                {
                    continue;
                }
                byte[] buffer = new byte[size];
                int    read   = 0;

                while ((read = nws.Read(buffer, 0, buffer.Length)) != 0)
                {
                    ms.Write(buffer, 0, read);
                }
                SurfaceWindow1.AddImage(System.Drawing.Image.FromStream(ms), tagColor);
            }
        }
コード例 #3
0
ファイル: Form1.cs プロジェクト: CGHill/Random-Projects
        public void ServerConnectThread()
        {
            updateUI("Server started, waiting for client");
            bluetoothListener = new BluetoothListener(mUUID);
            bluetoothListener.Start();
            conn = bluetoothListener.AcceptBluetoothClient();

            updateUI("Client has connected");
            connected = true;

            //Stream mStream = conn.GetStream();
            mStream = conn.GetStream();

            while (connected)
            {
                try
                {
                    byte[] received = new byte[1024];
                    mStream.Read(received, 0, received.Length);
                    string receivedString = Encoding.ASCII.GetString(received);
                    //updateUI("Received: " + receivedString);
                    handleBluetoothInput(receivedString);
                    //byte[] send = Encoding.ASCII.GetBytes("Hello world");
                    //mStream.Write(send, 0, send.Length);
                }
                catch (IOException e)
                {
                    connected = false;
                    updateUI("Client disconnected");
                    disconnectBluetooth();
                }
            }
        }
コード例 #4
0
        private async void button2_Click(object sender, EventArgs e)
        {
            BluetoothDevicePicker picker = new BluetoothDevicePicker();

            var device = await picker.PickSingleDeviceAsync();


            listBox1.Items.Clear();
            listBox2.Items.Clear();

            client = new InTheHand.Net.Sockets.BluetoothClient();
            client.Connect(device.DeviceAddress, new Guid("fa87c0d0-afac-11de-8a39-0800200c9a66"));
            stream      = client.GetStream();
            label3.Text = "Status: Connected " + device.DeviceName;

            //var AvilableDevices = client.DiscoverDevices();
            //foreach (var item in AvilableDevices)
            //{
            //    listBox1.Items.Add(item.DeviceName);
            //}



            //var PairDevices = client.PairedDevices;
            //foreach (var item in PairDevices)
            //{
            //    listBox2.Items.Add(item.DeviceName);
            //}

            btnConnect.Enabled    = !client.Connected;
            btnDisconnect.Enabled = client.Connected;
            btnSend.Enabled       = client.Connected;
        }
コード例 #5
0
        public static void GetImages(BluetoothEndPoint endpoint, Color tagColor)
        {
            InTheHand.Net.Sockets.BluetoothClient btc = new InTheHand.Net.Sockets.BluetoothClient();
            btc.Connect(endpoint);
            var nws = btc.GetStream();
            byte[] emptySize = BitConverter.GetBytes(0); //
            if (BitConverter.IsLittleEndian) Array.Reverse(emptySize); // redundant but usefull in case the number changes later..
            nws.Write(emptySize, 0, emptySize.Length); // write image size
            int imgCount = GetImgSize(nws);
            nws = btc.GetStream();
            for (int i = 0; i < imgCount; i++)
            {
                MemoryStream ms = new MemoryStream();
                int size = GetImgSize(nws);
                if (size == 0) continue;
                byte[] buffer = new byte[size];
                int read = 0;

                while ((read = nws.Read(buffer, 0, buffer.Length)) != 0)
                {
                    ms.Write(buffer, 0, read);
                }
                SurfaceWindow1.AddImage(System.Drawing.Image.FromStream(ms), tagColor);
            }
        }
コード例 #6
0
        /// <summary>
        /// Attempt to connect to the BluetoothDevice, without trying to pair first.
        /// </summary>
        /// <param name="device"></param>
        /// <returns></returns>
        public static async Task<Boolean> connectToDeviceWithoutPairing(BluetoothDevice device) {
            BluetoothEndPoint endPoint = new BluetoothEndPoint(device.btDeviceInfo.DeviceAddress, BluetoothService.SerialPort);
            BluetoothClient client = new BluetoothClient();
            if (!device.Authenticated) {
                return false;
            }
            else {
                try {
                    client.Connect(endPoint);

                    if (devicesStreams.Keys.Contains(device)) {
                        devicesStreams.Remove(device);
                    }
                    devicesStreams.Add(device, client.GetStream());

                    if (devicesClients.Keys.Contains(device)) {
                        devicesClients.Remove(device);
                    }
                    devicesClients.Add(device, client);
                }
                catch (Exception ex) {
                    //System.Console.Write("Could not connect to device: " + device.DeviceName + " " + device.DeviceAddress);
                    return false;
                }
                return true;
            }
        }
コード例 #7
0
ファイル: MainWindow.xaml.cs プロジェクト: ulebule/32feet
        private async void MainWindow_Activated(object sender, EventArgs e)
        {
            BluetoothDevicePicker picker = new BluetoothDevicePicker();
            //picker.ClassOfDevices.Add(new ClassOfDevice(DeviceClass.SmartPhone, 0));

            var device = await picker.PickSingleDeviceAsync();

            InTheHand.Net.Sockets.BluetoothClient client = new InTheHand.Net.Sockets.BluetoothClient();
            System.Diagnostics.Debug.WriteLine("Unknown");

            foreach (BluetoothDeviceInfo bdi in client.DiscoverDevices())
            {
                System.Diagnostics.Debug.WriteLine(bdi.DeviceName + " " + bdi.DeviceAddress);
            }

            System.Diagnostics.Debug.WriteLine("Paired");
            foreach (BluetoothDeviceInfo bdi in client.PairedDevices)
            {
                System.Diagnostics.Debug.WriteLine(bdi.DeviceName + " " + bdi.DeviceAddress);
            }


            //System.Diagnostics.Debug.WriteLine(client.RemoteMachineName);
            client.Connect(device.DeviceAddress, BluetoothService.SerialPort);
            var stream = client.GetStream();

            stream.Write(System.Text.Encoding.ASCII.GetBytes("Hello World\r\n\r\n"), 0, 15);
            stream.Close();
        }
コード例 #8
0
ファイル: BTUtils.cs プロジェクト: ArmyOfPirates/PS3BluMote
 public static List<string> GetNearbyRemoteAddresses(TimeSpan timeout)
 {
     List<string> result = new List<string>();
     try
     {
         BluetoothClient cli = new BluetoothClient();
         if (timeout != TimeSpan.Zero) cli.InquiryLength = timeout;
         BluetoothDeviceInfo[] devs = cli.DiscoverDevices();
         foreach (BluetoothDeviceInfo dev in devs)
         {
             if (dev.DeviceName.ToLower().Contains("bd remote control"))
             {
                 if (RemoteBtState(null, dev) == RemoteBtStates.Awake)
                 {
                     string candidate = FormatBtAddress(null, dev.DeviceAddress, "N");
                     if (!result.Contains(candidate)) result.Add(candidate);
                 }
             }
         }
     }
     catch
     {
         DebugLog.write("BTUtils.GetNearbyRemoteAddresses Failed");
     }
     return result;
 }
コード例 #9
0
        void findDevices()
        {
            List <Device> devices = new List <Device>();

            // po ponownym uruchomieniu
            if (comboBoxAvailableDevices.Items.Count > 0)
            {
                for (int i = 0; i < comboBoxAvailableDevices.Items.Count; i++)
                {
                    comboBoxAvailableDevices.Items.RemoveAt(i);
                }
            }

            InTheHand.Net.Sockets.BluetoothClient       bc    = new InTheHand.Net.Sockets.BluetoothClient();
            InTheHand.Net.Sockets.BluetoothDeviceInfo[] array = bc.DiscoverDevices();
            int count = array.Length;

            for (int i = 0; i < count; i++)
            {
                Device device = new Device(array[i]);
                devices.Add(device);
                comboBoxAvailableDevices.Items.Add(device);
            }

            if (count > 0)
            {
                comboBoxAvailableDevices.SelectedIndex = 0;
                buttonPair.Enabled = buttonSearch.Enabled = buttonSend.Enabled = true;
                ShowDeviceOnScreen();
            }
        }
コード例 #10
0
        public void readInfoClient()
        {
            bluetoothClient = bluetoothListener.AcceptBluetoothClient();
                    Console.WriteLine("Cliente Conectado!");

            Stream stream = bluetoothClient.GetStream();

            while (bluetoothClient.Connected)
                    {
                        try
                        {
                            byte[] byteReceived = new byte[1024];
                                int read = stream.Read(byteReceived, 0, byteReceived.Length);
                                if (read > 0)
                                {
                                    Console.WriteLine("Messagem Recebida: " + Encoding.ASCII.GetString(byteReceived) + System.Environment.NewLine);
                                }
                                stream.Flush();
                        }
                        catch (Exception e)
                        {
                                Console.WriteLine("Erro: " + e.ToString());
                        }
                    }
                    stream.Close();
        }
コード例 #11
0
 public void findBluetoothTolist()
 {
     BluetoothRadio.PrimaryRadio.Mode = RadioMode.Discoverable;
     BluetoothClient bluetoothClient = new BluetoothClient();
     BluetoothDeviceInfo[] bluetoothDeviceInfo = bluetoothClient.DiscoverDevices(10);
     ArrayList deviceCollection = new ArrayList();
     foreach (BluetoothDeviceInfo device_info in bluetoothDeviceInfo)
     {
         string device_name = device_info.DeviceName;
         string device_address = device_info.DeviceAddress.ToString();
         BluetoothDeviceManager manager = new BluetoothDeviceManager(device_name,device_address);
         deviceCollection.Add(manager);
     }
     System.Management.ManagementObjectSearcher Searcher = new System.Management.ManagementObjectSearcher("Select * from WIN32_SerialPort");
     foreach (System.Management.ManagementObject Port in Searcher.Get())
     {
         string PNPDeviceID = Port.GetPropertyValue("PNPDeviceID").ToString();
         string DeviceID = Port.GetPropertyValue("DeviceID").ToString();
         for (int i = 0; i < deviceCollection.Count; i++)
         {
             BluetoothDeviceManager manager = (BluetoothDeviceManager)deviceCollection[i];
             string device_address = manager.getDeviceAddress();
             int index = PNPDeviceID.IndexOf(device_address);
             if (index > 0)
             {
                 manager.addCOM(DeviceID);
                 bluetoothList.Add(manager);
             }
         }
     }
 }
コード例 #12
0
 public Arastirma(AnaPencere pencere)
 {
     anaPencere = pencere;
     localAygit = new BluetoothClient(); // Local bluetooth aygýtýna eriþiyoruz.
     aramaKanali = new Thread(new ThreadStart(AygitArama)); // Araþtýrma için iþ parçasý oluþtur.
     aramaKanali.Start(); // Ýþ parçasýný baþlat.
 }
コード例 #13
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);
		}
コード例 #14
0
        /// <summary>
        /// Bluetooth connection constructor
        /// </summary>
        private BluetoothConnection(ConnectionInfo connectionInfo, SendReceiveOptions defaultSendReceiveOptions, BluetoothClient btClient)
            : base(connectionInfo, defaultSendReceiveOptions)
        {
            if (btClient != null)
                this.btClient = btClient;

            dataBuffer = new byte[NetworkComms.InitialReceiveBufferSizeBytes];
        }
コード例 #15
0
ファイル: Singleton.cs プロジェクト: slodge/BallControl
        public string[] GetAvailableSpheroNames()
        {
            Reset();

            _client = new BluetoothClient();
            _peers = _client.DiscoverDevices();
            var spheros = _peers.Where(x => x.DeviceName.StartsWith("Sphero")).Select(x => x.DeviceName).ToArray();
            return spheros;
        }
コード例 #16
0
        public void Disconnect()
        {
            _client.Close();
              _client = new BluetoothClient();

              _readerThread = null;
              _reader = null;
              _writer = null;
        }
コード例 #17
0
        void bg_DoWork(object sender, DoWorkEventArgs e)
        {
            /*
             * Loop over the list of all detected bluetooth devices and display them for selecion
             * by the user .
             */
            ObservableCollection <Device> devices = new ObservableCollection <Device>();

            // Check if a Bluetooth radio is available on the system that is compatible with the 32Feet library.
            // If not then exit.

            log.dispatchLogMessage("Bluetooth_Devices: Attempting to find a Bluetooth radio ");
            bool d = BluetoothRadio.IsSupported;

            if (!d)
            {
                var msg = "No compatible Bluetooth radio found on system . Aboring application";
                log.dispatchLogMessage(msg);
                System.Windows.Forms.MessageBox.Show(msg);
                Environment.Exit(1);
            }
            log.dispatchLogMessage("Success! Compatibe Bluetooth radio found on system ");
            BluetoothRadio br    = BluetoothRadio.PrimaryRadio;
            var            messg = "Details of the Bluetooth radio : ";

            log.dispatchLogMessage(messg);
            // Manfucaturer
            messg = "Manufacturer : " + br.Manufacturer.ToString();
            log.dispatchLogMessage(messg);

            // System Name
            messg = "Name : " + br.Name.ToString();
            log.dispatchLogMessage(messg);

            //Software Manufacturer
            messg = "Software Manufacturer :" + br.SoftwareManufacturer.ToString();
            log.dispatchLogMessage(messg);
            log.dispatchLogMessage("Bluetooth Radio initiated");
            log.dispatchLogMessage("***");

            // This must be put in a try block
            InTheHand.Net.Sockets.BluetoothClient       bc    = new InTheHand.Net.Sockets.BluetoothClient();
            InTheHand.Net.Sockets.BluetoothDeviceInfo[] array = bc.DiscoverDevices();
            log.dispatchLogMessage("Bluetooth_Devices: Bluetooth Devices found  in vicinity");

            int    count = array.Length;
            Device device;

            for (int i = 0; i < count; i++)
            {
                device = new Device(array[i]);
                devices.Add(device);
                //UnsecuredDevices.Add(device);
            }
            _unsecuredDevices = devices;
            e.Result          = _unsecuredDevices;
        }
コード例 #18
0
		public WinBluetoothConnection()
		{
			connectedDeviceInfo = null;
			connection = new BluetoothClient();
			bluetoothAddress = 0;

            socketIsReadyToNewRecive = true;
            socketIsReadyToNewSend = true;
		}
コード例 #19
0
ファイル: MainForm.cs プロジェクト: tewarid/NetTools
        private void Initialize()
        {
            client = new BluetoothClient();
            devices = client.DiscoverDevices(10, true, true, false);

            deviceList.Items.Clear();
            foreach (BluetoothDeviceInfo device in devices)
            {
                deviceList.Items.Add(device.DeviceName);
            }
        }
コード例 #20
0
ファイル: PebbleNet45.cs プロジェクト: mubold/PebbleSharp
 public Task OpenAsync()
 {
     return Task.Run( () =>
     {
         _tokenSource = new CancellationTokenSource();
         _client = new BluetoothClient();
         _client.Connect( _deviceInfo.DeviceAddress, BluetoothService.SerialPort );
         _networkStream = _client.GetStream();
         Task.Factory.StartNew( CheckForData, _tokenSource.Token, TaskCreationOptions.LongRunning,
             TaskScheduler.Default );
     } );
 }
コード例 #21
0
ファイル: PebbleNet45.cs プロジェクト: mubold/PebbleSharp
        public static IList<Pebble> DetectPebbles()
        {
            var client = new BluetoothClient();

            // A list of all BT devices that are paired, in range, and named "Pebble *" 
            var bluetoothDevices = client.DiscoverDevices( 20, true, false, false ).
                Where( bdi => bdi.DeviceName.StartsWith( "Pebble " ) ).ToList();

            return ( from device in bluetoothDevices
                     select (Pebble)new PebbleNet45( new PebbleBluetoothConnection( device ),
                         device.DeviceName.Substring( 7 ) ) ).ToList();
        }
コード例 #22
0
 public static void SendBluetooth(BluetoothEndPoint endpoint, BitmapSource bms)
 {
     InTheHand.Net.Sockets.BluetoothClient btc = new InTheHand.Net.Sockets.BluetoothClient();
     btc.Connect(endpoint);
     byte[] img = BmSourceToByteArr(bms);
     var nws = btc.GetStream();
     byte[] imgSize = BitConverter.GetBytes(img.Length);
     if (BitConverter.IsLittleEndian) Array.Reverse(imgSize);
     nws.Write(imgSize, 0, imgSize.Length); // write image size
     nws.Write(img, 0, img.Length); // Write image
     nws.Flush();
 }
コード例 #23
0
        void bg_DoWork(object sender, DoWorkEventArgs e)
        {
            InTheHand.Net.Sockets.BluetoothClient       bc    = new InTheHand.Net.Sockets.BluetoothClient();
            InTheHand.Net.Sockets.BluetoothDeviceInfo[] array = bc.DiscoverDevices();
            int count = array.Length;

            for (int i = 0; i < count; i++)
            {
                Device device = new Device(array[i]);
                detectedDevices.Add(device);
            }
        }
コード例 #24
0
        public IstemciDinleyici(BluetoothClient istemci, AnaPencere pencere)
        {
            this.istemci = istemci;
            this.anaPencere = pencere;

            istemciAdi = this.istemci.RemoteMachineName;
            istemciAdresi = ((BluetoothEndPoint)(this.istemci.Client.RemoteEndPoint)).Address; // :D

            anaPencere.SunucuUyariGoster("Ýstemci baðlandý: " + istemciAdi);

            istemciKanali = new Thread(new ThreadStart(Kanal));
            istemciKanali.Start();
        }
コード例 #25
0
ファイル: BlueToothStream.cs プロジェクト: cail/hobd
 public void Close()
 {
     if (bluetoothClient != null)
     {
     bluetoothClient.Close();
     bluetoothClient = null;
     }
     if (stream != null)
     {
     stream.Close();
     stream = null;
     }
 }
コード例 #26
0
 private void bg_DoWork(object sender, DoWorkEventArgs e)
 {
     List<Device> devices = new List<Device>();
     InTheHand.Net.Sockets.BluetoothClient bc = new InTheHand.Net.Sockets.BluetoothClient();
     InTheHand.Net.Sockets.BluetoothDeviceInfo[] array = bc.DiscoverDevices();
     int count = array.Length;
     for (int i = 0; i < count; i++)
     {
         Device device = new Device(array[i]);
         devices.Add(device);
     }
     e.Result = devices;
 }
コード例 #27
0
ファイル: Program.cs プロジェクト: kakkr1/ProjectOneLan
        static void Main(string[] args)
        {
            //Runs Method
               InitDeviceList();

               //Drops known user table
               sqlClient.Drop("tblknown");
               //Creates known user table
               sqlClient.Create("tblknown", "id int NOT NULL AUTO_INCREMENT, name varchar(255),counting int NOT NULL ,address int,PRIMARY KEY (id)");

               BluetoothClient bc = new BluetoothClient();
               BluetoothDeviceInfo[] devices = bc.DiscoverDevices();

                   string a = "dadasd";
                   int number = 0;

                   if (devices.Length == 0)
                   {
                       Console.WriteLine("Empty set");
                   }
                   else

                       for (int i = 0; i < devices.Length; i++)
                       {
                           a = number + ") " + devices[i].DeviceName + "/" + "Address: " + devices[i].DeviceAddress + "\r\n";

                           for (int j = 0; j < userDevices.Count; j++)
                           {
                               if (devices[i].DeviceAddress.ToString() == userDevices[j].Address)
                               {
                                   //convert list items to string
                                   string username = (userDevices[j].UserName.ToString().ToUpper());
                                   string address = (userDevices[j].Address.ToString().ToUpper());
                                   //adds '' to string,so sql can accept as a char
                                   string knownuser = "******" + username.Replace(",", "','") + "'";
                                   string knownaddress = "'" + address.Replace(",", "','") + "'";

                                   //  listBox1.Items.Add(userDevices[j].UserName);

                                   sqlClient.Insert("tblknown", "name", knownuser);
                                   sqlClient.Update("tblknown", "counting =counting+1", "id=1");
                               }

                           }

                           number++;
                           Console.WriteLine(a);

                       }
                   Console.ReadLine();
        }
コード例 #28
0
        /// <summary>
        /// Internal <see cref="BluetoothConnection"/> creation which hides the necessary internal calls
        /// </summary>
        /// <param name="connectionInfo">ConnectionInfo to be used to create connection</param>
        /// <param name="defaultSendReceiveOptions">Connection default SendReceiveOptions</param>
        /// <param name="btClient">If this is an incoming connection we will already have access to the btClient, otherwise use null</param>
        /// <param name="establishIfRequired">Establish during create if true</param>
        /// <returns>An existing connection or a new one</returns>
        internal static BluetoothConnection GetConnection(ConnectionInfo connectionInfo, SendReceiveOptions defaultSendReceiveOptions, BluetoothClient btClient, bool establishIfRequired = true)
        {
            connectionInfo.ConnectionType = ConnectionType.Bluetooth;

            //If we have a tcpClient at this stage we must be server side
            if (btClient != null) connectionInfo.ServerSide = true;

            bool newConnection = false;
            BluetoothConnection connection;

            lock (NetworkComms.globalDictAndDelegateLocker)
            {
                List<Connection> existingConnections = NetworkComms.GetExistingConnection(connectionInfo.RemoteEndPoint, connectionInfo.LocalEndPoint, connectionInfo.ConnectionType, connectionInfo.ApplicationLayerProtocol);

                //Check to see if a connection already exists, if it does return that connection, if not return a new one
                if (existingConnections.Count > 0)
                {
                    if (NetworkComms.LoggingEnabled)
                        NetworkComms.Logger.Trace("Attempted to create new BluetoothConnection to connectionInfo='" + connectionInfo + "' but there is an existing connection. Existing connection will be returned instead.");

                    establishIfRequired = false;
                    connection = (BluetoothConnection)existingConnections[0];
                }
                else
                {
                    if (NetworkComms.LoggingEnabled)
                        NetworkComms.Logger.Trace("Creating new BluetoothConnection to connectionInfo='" + connectionInfo + "'." + (establishIfRequired ? " Connection will be established." : " Connection will not be established."));

                    if (connectionInfo.ConnectionState == ConnectionState.Establishing)
                        throw new ConnectionSetupException("Connection state for connection " + connectionInfo + " is marked as establishing. This should only be the case here due to a bug.");

                    //If an existing connection does not exist but the info we are using suggests it should we need to reset the info
                    //so that it can be reused correctly. This case generally happens when using NetworkComms.Net in the format 
                    //TCPConnection.GetConnection(info).SendObject(packetType, objToSend);
                    if (connectionInfo.ConnectionState == ConnectionState.Established || connectionInfo.ConnectionState == ConnectionState.Shutdown)
                        connectionInfo.ResetConnectionInfo();

                    //We add a reference to networkComms for this connection within the constructor
                    connection = new BluetoothConnection(connectionInfo, defaultSendReceiveOptions, btClient);
     
                    newConnection = true;
                }
            }

            if (newConnection && establishIfRequired) connection.EstablishConnection();
            else if (!newConnection) connection.WaitForConnectionEstablish(NetworkComms.ConnectionEstablishTimeoutMS);

            if (!NetworkComms.commsShutdown) TriggerConnectionKeepAliveThread();

            return connection;
        }
        //private static BlueToothWorker _worker = new BlueToothWorker();
        public static string[] GetDevicesinRange()
        {
            var result = new List<string>();
            var cli = new InTheHand.Net.Sockets.BluetoothClient();

            //cli.BeginDiscoverDevices(10, true, true, false, false, DeviceDiscovered, null);
            var peers = cli.DiscoverDevices();
            foreach (var device in peers)
            {
                result.Add(device.DeviceName);
            }

            return result.ToArray();
        }
コード例 #30
0
ファイル: Singleton.cs プロジェクト: slodge/BallControl
        public void Reset()
        {
            if (_stream != null)
            {
                _stream.Dispose();
                _stream = null;
            }

            if (_client != null)
            {
                _client.Dispose();
                _client = null;
            }
        }
コード例 #31
0
 private void Scanner()
 {
   
     updateUI("Starting Scan...");
     BluetoothClient client = new BluetoothClient();
     devices = client.DiscoverDevicesInRange();
     updateUI("Scan complete");
     updateUI(devices.Length.ToString() + " devices discovered");
     foreach(BluetoothDeviceInfo d in devices)
     {
         items.Add(d.DeviceName);
     }
     updateDeviceList();
 }
コード例 #32
0
 public bool? deviceIsRuning()
 {
     bool? result = null;
     try
     {
         BluetoothClient searcher = new BluetoothClient();
         searcher.DiscoverDevices();
         return true;
     }
     catch (Exception ex)
     {
         result = false;
     }
     return result;
 }
コード例 #33
0
ファイル: Form1.cs プロジェクト: katadam/wockets
        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);
            }
        }
コード例 #34
0
        public static void SendBluetooth(BluetoothEndPoint endpoint, BitmapSource bms)
        {
            InTheHand.Net.Sockets.BluetoothClient btc = new InTheHand.Net.Sockets.BluetoothClient();
            btc.Connect(endpoint);
            byte[] img = BmSourceToByteArr(bms);
            var    nws = btc.GetStream();

            byte[] imgSize = BitConverter.GetBytes(img.Length);
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(imgSize);
            }
            nws.Write(imgSize, 0, imgSize.Length); // write image size
            nws.Write(img, 0, img.Length);         // Write image
            nws.Flush();
        }
コード例 #35
0
        void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            List <String>   devicesNames = new List <String>();
            BluetoothClient bc           = new InTheHand.Net.Sockets.BluetoothClient();

            BluetoothDeviceInfo[] array = bc.DiscoverDevices(10);
            int count = array.Length;

            for (int i = 0; i < count; i++)
            {
                //Device device = new Device(array[i]);
                devices.Add(array[i]);
                devicesNames.Add(array[i].DeviceName);
            }
            e.Result = devicesNames;
        }
コード例 #36
0
ファイル: AvailableSphero.cs プロジェクト: slodge/BallControl
 private async void DoConnect(Action<IConnectedSphero> onSuccess, Action<Exception> onError)
 {
     try
     {
         var serviceClass = BluetoothService.SerialPort;
         var ep = new BluetoothEndPoint(PeerInformation.DeviceAddress, serviceClass);
         var client = new BluetoothClient();
         client.Connect(ep);
         var stream = client.GetStream();
         onSuccess(new ConnectedSphero(PeerInformation, stream));
     }
     catch (Exception exception)
     {
         onError(exception);
     }
 }
コード例 #37
0
 void ServerWorker_DoWork(object sender, DoWorkEventArgs e)
 {
     try
     {
         client = serverSocket.AcceptBluetoothClient();
         Stream peerStream = client.GetStream();
         bWriter = new BinaryWriter(peerStream, Encoding.ASCII);
         bReader = new BinaryReader(peerStream, Encoding.ASCII);
         e.Result = true;
     }
     catch (Exception exception)
     {
         e.Result = false;
         Console.WriteLine(exception.Message);
     }
 }
コード例 #38
0
        private void btnDeviceDiscovery_Click(object sender, EventArgs e)
        {
            if (!BluetoothRadio.IsSupported)
            {
                MessageBox.Show("Adapter not found");
            }
            else
            {
                InTheHand.Net.Sockets.BluetoothClient bc = new InTheHand.Net.Sockets.BluetoothClient();

                InTheHand.Net.Sockets.BluetoothDeviceInfo[] array = bc.DiscoverDevices();
                for (int i = 0; i < array.Length; i++)
                {
                    this.address_array[i] = array[i].DeviceAddress;
                    this.lsDevices.Items.Add(array[i].DeviceName);
                }
            }
        }
コード例 #39
0
        private void bluetooth_Load(object sender, EventArgs e)
        {
            try
            {
                if (BluetoothRadio.IsSupported)
                {
                    bluetoothClient = new InTheHand.Net.Sockets.BluetoothClient();

                    if (BluetoothRadio.PrimaryRadio.Mode == RadioMode.PowerOff)
                    {
                        BluetoothRadio.PrimaryRadio.Mode = RadioMode.Connectable;
                    }
                }
                else
                {
                    MessageBox.Show("Adaptar is not detected");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
コード例 #40
0
ファイル: Form2.cs プロジェクト: fknince/AdilKullanimSoft
        public void klimaKapamaTalebi(String name, InTheHand.Net.Sockets.BluetoothClient bc)
        {
            DialogResult dr = MessageBox.Show(name + " adlı kullanıcı klima kapama talebinde bulunuyor.Klima kapansın mı ?",
                                              "Klima Kapama Talebi ", MessageBoxButtons.YesNo);

            switch (dr)
            {
            case DialogResult.Yes:
            {
                if (isKlima)
                {
                    bcc.sendMessageToClient("kli#kapa#yes", bc);
                    this.setText("Klima kapandı.");
                    pictureBox3.Image = Image.FromFile("C:/Users/fince/Documents/Visual Studio 2017/Projects/GZSProjesiC#/GZSProjesi/images/fanStopping.png");
                    ac.gonder("kapaK");
                    isKlima = false;
                }


                break;
            }

            case DialogResult.No:
            {
                if (isKlima)
                {
                    bcc.sendMessageToClient("kli#kapa#false", bc);
                    this.setText("Klima kapanmadı.");
                    isKlima = true;
                }


                break;
            }
            }
        }
コード例 #41
0
ファイル: AdminWindow.xaml.cs プロジェクト: oldsmokingjoe/YQ
        void doBluetoothWork(String deviceName)
        {
            // Check if a Bluetooth radio is available on the system that is compatible with the 32Feet library.
            // If not then exit.
            log.dispatchLogMessage("Mainservices : Attempting to find a Bluetooth radio ");
            bool d = BluetoothRadio.IsSupported;

            if (!d)
            {
                var msg = "No compatible Bluetooth radio found on system . Aboring application";
                log.dispatchLogMessage(msg);
                System.Windows.Forms.MessageBox.Show(msg);
                Environment.Exit(1);
            }
            log.dispatchLogMessage("Mainservices : Success! Compatibe Bluetooth radio found on system ");

            BluetoothRadio br    = BluetoothRadio.PrimaryRadio;
            var            messg = "Mainservices : Details of the Bluetooth radio : ";

            log.dispatchLogMessage(messg);
            // Manfucaturer
            messg = "Mainservices : Manufacturer : " + br.Manufacturer.ToString();
            log.dispatchLogMessage(messg);

            // System Name
            messg = "Mainservices : Name : " + br.Name.ToString();
            log.dispatchLogMessage(messg);

            //Software Manufacturer
            messg = "Mainservices : Software Manufacturer :" + br.SoftwareManufacturer.ToString();
            log.dispatchLogMessage(messg);
            log.dispatchLogMessage("Mainservices : Bluetooth Radio initiated");
            log.dispatchLogMessage("***");

            // This must be put in a try block
            InTheHand.Net.Sockets.BluetoothClient       bc    = new InTheHand.Net.Sockets.BluetoothClient();
            InTheHand.Net.Sockets.BluetoothDeviceInfo[] array = bc.DiscoverDevices();
            log.dispatchLogMessage("Mainservices : Bluetooth Devices found  in vicinity");

            int count = array.Length;
            BluetoothDeviceInfo dev;

            for (int i = 0; i < count; i++)
            {
                Device device = new Device(array[i]);
                if (device.DeviceName == deviceName)
                {
                    /*
                     * Here the maxTries refers to the number of times we will make an attempt to "connect" to the device . Later
                     * the maxTries refer to the number of times we will make an attemp to "checkconnection" that was established earlier.
                     */
                    int attempts = 0;
                    int maxTries = 3;


                    while (attempts < maxTries)
                    {
                        log.dispatchLogMessage("Mainservices : Found a Bluetooth device to connect to ");
                        log.dispatchLogMessage("Mainservices : Attempting connection to : " + deviceName);
                        dev = array[i];

                        var addr = device.DeviceAddress;
                        if (addr == null)
                        {
                            return;
                        }

                        Guid serviceClass = BluetoothService.SerialPort;

                        // Make a connection to the bluetooth device and continously check for pairing
                        //

                        // Make a connection to the specified Bluetooth device
                        try
                        {
                            connectBluetoothDevice(bc, addr, serviceClass);


                            /*
                             * Here we fetch the RSSI values of the strength of the signal established betweem the system
                             * and bluetooth device . Currently we just log it . Maybe later we make more better use of it.
                             */
                            try
                            {
                                int sigStrgt = dev.Rssi;
                                var mssg     = "Mainservices : Signal strength of the connection is" + sigStrgt;
                                log.dispatchLogMessage(mssg);
                            }
                            catch (Exception e)
                            {
                                /*
                                 * Rssi query may fail on certain platforms . Check http://inthehand.com/library/html/P_InTheHand_Net_Sockets_BluetoothDeviceInfo_Rssi.htm
                                 * for platfrom details . Handle failure gracefully.
                                 */
                                var mssg = e.Message;
                                mssg += "Mainservices : Signal strength cannot be determined";
                                log.dispatchLogMessage(mssg);
                            }

                            checkconnection(dev, serviceClass, bc);

                            /*
                             * If you fall out from checkconnection you probably mean that the connection no longer exits .
                             * So increment attempts.
                             */
                            attempts++;
                        }
                        catch (Exception ex)
                        {
                            // handle exception
                            attempts++;
                            var msg = "Mainservices : Bluetooth connection failed: " + ex.Message;
                            log.dispatchLogMessage(msg);
                            log.dispatchLogMessage("Mainservices : Re-initiating connection");
                            msg = "Mainservices : Attempt " + attempts;
                            log.dispatchLogMessage(msg);
                        }
                    }
                }
            }
        }
コード例 #42
0
        void doBluetoothWork()
        {
            int attempts = 0;
            int maxTries = 1;


            while (attempts < maxTries)
            {
                attempts++;
                List <Device> devices = new List <Device>();
                // Check if a Bluetooth radio is available on the system that is compatible with the 32Feet library.
                // If not then exit.
                log.dispatchLogMessage("Bluetooth Devices: Attempting to find a Bluetooth radio ");
                bool d = BluetoothRadio.IsSupported;
                if (!d)
                {
                    var msg = "No compatible Bluetooth radio found on system . Aboring application";
                    log.dispatchLogMessage(msg);
                    System.Windows.Forms.MessageBox.Show(msg);
                    Environment.Exit(1);
                }
                log.dispatchLogMessage("Success! Compatibe Bluetooth radio found on system ");
                BluetoothRadio br    = BluetoothRadio.PrimaryRadio;
                var            messg = "Details of the Bluetooth radio : ";
                log.dispatchLogMessage(messg);
                // Manfucaturer
                messg = "Manufacturer : " + br.Manufacturer.ToString();
                log.dispatchLogMessage(messg);

                // System Name
                messg = "Name : " + br.Name.ToString();
                log.dispatchLogMessage(messg);

                //Software Manufacturer
                messg = "Software Manufacturer :" + br.SoftwareManufacturer.ToString();
                log.dispatchLogMessage(messg);
                log.dispatchLogMessage("Bluetooth Radio initiated");
                log.dispatchLogMessage("***");

                // This must be put in a try block
                InTheHand.Net.Sockets.BluetoothClient       bc    = new InTheHand.Net.Sockets.BluetoothClient();
                InTheHand.Net.Sockets.BluetoothDeviceInfo[] array = bc.DiscoverDevices();
                log.dispatchLogMessage("Bluetooth Devices found  in vicinity");

                int count = array.Length;
                BluetoothDeviceInfo dev;
                for (int i = 0; i < count; i++)
                {
                    Device device = new Device(array[i]);
                    if (device.DeviceName == "SAMSUNG GT-I8350")
                    {
                        log.dispatchLogMessage("Found a PROTAG device to connect to ");
                        dev = array[i];

                        var addr = device.DeviceAddress;
                        if (addr == null)
                        {
                            return;
                        }

                        Guid serviceClass = BluetoothService.SerialPort;

                        // Make a connection to the bluetooth device and continously check for pairing
                        // Lets make 3 consecutive checks to ensure that the connection still exists .

                        // Make a connection to the specified Bluetooth device
                        try
                        {
                            connectBluetoothDevice(bc, addr, serviceClass);


                            try
                            {
                                int sigStrgt = dev.Rssi;
                                var mssg     = "Signal strength of the connection is" + sigStrgt;
                                log.dispatchLogMessage(mssg);
                            }
                            catch (Exception e)
                            {
                                /*
                                 * Rssi query may fail on certain platforms . Check http://inthehand.com/library/html/P_InTheHand_Net_Sockets_BluetoothDeviceInfo_Rssi.htm
                                 * for platfrom details . Handle failure gracefully.
                                 */
                                var mssg = e.Message;
                                mssg += "Signal strength cannot be determined";
                                log.dispatchLogMessage(mssg);
                            }

                            checkconnection(dev, serviceClass, bc);
                        }
                        catch (Exception ex)
                        {
                            // handle exception

                            var msg = "Bluetooth connection failed: " + ex.Message;
                            log.dispatchLogMessage(msg);
                            log.dispatchLogMessage("Re-initiating connection");
                            msg = "Attempt " + attempts;
                            log.dispatchLogMessage(msg);
                            Thread.Sleep(10);
                        }
                    }
                    devices.Add(device);
                }
                if (attempts >= maxTries)
                {
                }
                //e.Result = devices;
            }
            var mesg = "Bluetooth pairing is broken . Please check ! ";

            log.dispatchLogMessage(mesg);
            LockWorkStation();
        }
コード例 #43
0
 private void Form1_Load(object sender, EventArgs e)
 {
     InTheHand.Net.Sockets.BluetoothClient bc = new InTheHand.Net.Sockets.BluetoothClient();
 }
コード例 #44
-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...");
 }