Click here to Skip to main content
15,886,067 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have done the youtube tutorial https://www.youtube.com/watch?v=9LG9Kfythu4[^]
but i did not geht a connection to my device on the other side. can somebody help me? what i´m doing wrong?

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Windows;
using InTheHand;
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Ports;
using InTheHand.Net.Sockets;
using System.IO;
using InTheHand.Net;

namespace HL7000_Prüf
{
    public partial class Form1 : Form
    {
        List<string> items;
        public Form1()
        {
            items = new List<string>();
            InitializeComponent();
        }

        private void bGo_Click(object sender, EventArgs e)
        {
            if (serverStarted)
            {
                updateUI("server has started");
                return;
            }
            if (rbClient.Checked)
            {
                startScan();
            }
            else
            {
                connectAsServer();
            }
        }

        private void startScan()
        {
            listBox1.DataSource = null;
            listBox1.Items.Clear();
            items.Clear();
            Thread bluetoothScanThread = new Thread(new ThreadStart(scan));
            bluetoothScanThread.Start();
        }


        BluetoothDeviceInfo[] devices;
        private void scan()
        {
           
            updateUI("Starting Scan..");
            BluetoothClient client = new BluetoothClient();
            devices = client.DiscoverDevicesInRange();
           // devices = client.DiscoverDevicesInRange();
            updateUI("Scan complete");
            updateUI(devices.Length.ToString() + " devices discovered");

            foreach (BluetoothDeviceInfo d in devices)
            {

                string desc = d.DeviceName + ": " + d.DeviceAddress;


                items.Add(desc);
            }
            updateDeviceList();
        }

        private void connectAsServer()
        {
            Thread bluetoothServerThread = new Thread(new ThreadStart(ServerConnectThread));
            bluetoothServerThread.Start();
        }

        private void connectAsClient()
        {
            throw new NotImplementedException();
        }

        
        Guid mUUID = new Guid("00011111-0000-1000-8000-00805F9B34FB");
       // Guid mUUID = new Guid("00001101-0000-1000-8000-00805f9b34fb");
       // Guid mUUID = new Guid("e0cbf06c-cd8b-4647-bb8a-263b43f0f974");
//        Guid mUUID = System.Guid.NewGuid();
        bool serverStarted = false;
        public void ServerConnectThread()
        {
            serverStarted = true;
            updateUI("Server started, waiting for clients");

            BluetoothListener blueListener = new BluetoothListener(mUUID);
            
            blueListener.Start();
       
            BluetoothClient conn = blueListener.AcceptBluetoothClient();
            MessageBox.Show(blueListener.Authenticate.ToString());
            updateUI("Client has Connected");
          
            Stream mStream = conn.GetStream();
            while (true)
            {
                try
                {
                    //handle sever connection
                    byte[] received = new byte[1024];
                    mStream.Read(received, 0, received.Length);
                    updateUI("received: " + Encoding.ASCII.GetString(received));
                    byte[] sent = Encoding.ASCII.GetBytes("hello World");
                    mStream.Write(sent, 0, sent.Length);
                }
                catch (IOException exeption)
                {
                    updateUI("Client has disconnected");
                }
            }
        }

        private void updateUI(string message)
        {
            Func<int> del = delegate()
            {
                tbOutput.AppendText(message + System.Environment.NewLine);

                return 0;
            };
            Invoke(del);
         
        }
        private void updateDeviceList()
        {
            Func<int> del = delegate()
            {
                listBox1.DataSource = items;
                return 0;
            };
           Invoke(del);
        }


        BluetoothDeviceInfo deviceInfo;
        private void listBox1_DoubleClick(object sender, EventArgs e)
        {
            deviceInfo = devices.ElementAt(listBox1.SelectedIndex);
            updateUI(deviceInfo.DeviceName + " was selected");

            if (pairDevice())
            {
                updateUI("device paired..");
                updateUI("starting connect thread");
                Thread bluetoothClientThread = new Thread(new ThreadStart(ClientConnectThread));
                bluetoothClientThread.Start();
            }
            else
            {
                updateUI("Pair failed");
            }
        }

        private void ClientConnectThread()
        {
            BluetoothClient client = new BluetoothClient();
            updateUI("attempting connect");
            client.BeginConnect(deviceInfo.DeviceAddress, mUUID, this.BluetoothClientConnectCallback, client);
            if (client.Connected)
            {
                updateUI("Verbindung geht");
            }
            else
            {
                updateUI("nicht");
            }
        }

        void BluetoothClientConnectCallback(IAsyncResult result)
        {

            BluetoothClient client = (BluetoothClient)result.AsyncState;
            client.EndConnect(result);

            Stream stream = client.GetStream();
            stream.ReadTimeout = 1000;

            while (true)
            {
                while (!ready) ;

                stream.Write(message, 0, message.Length);
            }
        }

        string myPin = "1234";
        private bool pairDevice()
        {
            if (!deviceInfo.Authenticated)
            {
                if (!BluetoothSecurity.PairRequest(deviceInfo.DeviceAddress, myPin))
                {
                    return false;
                }
            }
            return true;
        }
        bool ready = false;
        byte[] message;
        private void tbText_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                message = Encoding.ASCII.GetBytes(tbText.Text);
                ready = true;
                tbText.Clear();
            }
        }

    }
}


I wrote in C#. The Guid that i set in Comment i had tried, but i think there is something wrong because the messagebox after
C#
BluetoothClient conn = blueListener.AcceptBluetoothClient();
would not be shown.

thank for your help

What I have tried:

different Guid, the Server Connection will be failed.
Posted
Updated 12-Dec-16 2:28am

From the 32feet.NET documentation:
Quote:
Bluetooth applications/services are identified and registered by UUID (Universally Unique Id), a 128-bit value that is represented by the System.Guid class in .NET. If one is creating a new service then a new UUID should be created at design time and entered into the two applications’ source code, a new value can be created either by calling Guid.NewValue or using the guidgen.exe Windows SDK program — in Visual Studio access it with menu item Tools, “Create GUID”.


Finally a maybe stupid question:
Have you also started a client instance on another device using the same UUID?
If not, the server will of course wait indefinitly for a connection.

[EDIT Answering a question posted as solution]
Quote:
this is all of my code. how do i get the uuid? and how do i start the client instance when the server isn´t ready?

To generate an UUID follow the advices from the quote (execute the guidgen.exe tool and copy and paste the UUID or use Guid.NewGuid Method (System)[^])

The server is ready when starting the application as server. It just waits for a connection. AcceptBluetoothClient is a blocking call. That means the call will not return until a connection has been established or an error occured. Therefore, it is called from within it's own thread.

Then start the software as client on another system (rbClient.Checked must be true). It should then connect (or at least try) to connect to the server. I have not tried to understand what all the code is doing. And it seems you have neither.

Bluetooth is a serial radio protocol. As far as I know it does not support being client and server on a single system (as most serial protocols / interfaces like IrDA, USB, RS-232 without using some kind of loopback hardware). So you have to start two (or more) instances of your application on two different systems (or using two Bluetooth devices connected to one system): One server and one or more clients.
[/EDIT]
 
Share this answer
 
v2
this is all of my code. how do i get the uuid? and how do i start the client instance when the server isn´t ready?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900