Bluetooth SPP Client端

1 篇文章 / 0 new
author
Bluetooth SPP Client端
Client的處理程序則稍多, 包含藍芽裝置的清單取得, 配對驗證與連線
► 藍芽裝置清單
private void startScan()
{
    bOpen.Enabled = false;
    Thread bluetoothScanThread = new Thread(new ThreadStart(scan));
    bluetoothScanThread.Start();
}
BluetoothDeviceInfo[] devices;
private void scan()
{
    listBox1.DataSource = null;
    //開始搜索藍芽裝置
    try
    {
        BluetoothClient client = new BluetoothClient();
        devices = client.DiscoverDevicesInRange();
        //搜索完成
        foreach (BluetoothDeviceInfo d in devices)
        {
            var output = string.Join(":", Enumerable.Range(0, 6).Select(i => d.DeviceAddress.ToString().Substring(i * 2, 2)));
            items.Add(String.Format("[{1}] {0}", d.DeviceName, output));
        }
    }
    catch (Exception e) {}
    updateDeviceList();
}
► 配對驗證
BluetoothDeviceInfo deviceInfo;
private void listBox1_DoubleClick(object sender, EventArgs e)
{
    deviceInfo = devices.ElementAt(listBox1.SelectedIndex);
    //連結/取消連結 到 com port
    deviceInfo.SetServiceState(BluetoothService.SerialPort, cbLinkComPort.Checked, false);
    if (cbLinkComPort.Checked)
        return;
    if (pairDevice())
    {
        Thread bluetoothClientThrad = new Thread(new ThreadStart(ClientConnectThread));
        bluetoothClientThrad.Start();
    }
    else
    {
        //配對失敗
    }
}
String myPIN = "138922";//尚不知用途為何
private bool pairDevice()
{
    if (!deviceInfo.Authenticated)
    {
        updateUI("裝置配對中..");
        if (!BluetoothSecurity.PairRequest(deviceInfo.DeviceAddress, myPIN))
            return false;
    }
    return true;
}
► 連接
private void ClientConnectThread()
{
    BluetoothClient client = new BluetoothClient();
    //準備連接裝置
    client.BeginConnect(deviceInfo.DeviceAddress, mUUID, this.BluetoothClientConnectCallBack, client);
}
private void BluetoothClientConnectCallBack(IAsyncResult ar)
{
    //開始連線
    BluetoothClient client = (BluetoothClient)ar.AsyncState;
    try
    {
        client.EndConnect(ar);
        try
        {
            //連線完成
            Stream stream = client.GetStream();
            stream.ReadTimeout = 1000;
            byte[] received = new byte[1024];
            while (clientStart)
            {
                try
                {
                    int l = stream.Read(received, 0, received.Length);
                    if (l > 0)
                        String data = Encoding.Unicode.GetString(received, 0, l));
                }
                catch (Exception e) { }
                while (ready)
                { //[傳送]
                    stream.Write(message, 0, message.Length);
                    ready = false;
                }
                Thread.Sleep(100);
            }
            stream.Close();
            stream.Dispose();
        }
        catch (Exception e1) { }
        client.Close();
    }
    catch (Exception ce)   { //連線錯誤, 通常錯誤為對方沒有提供所需類型的服務
        client.Close();
    }
}
關鍵字: 
Free Web Hosting