EMDK Bluetooth LocalDevices - PullRequest
       24

EMDK Bluetooth LocalDevices

0 голосов
/ 10 июня 2011

Просто быстрый вопрос, как я могу получить локальные устройства Bluetooth, которые уже были сопряжены, используя EMDK 2.4 Motorola для устройства MC75? Кажется, я могу получить список RemoteDevice, но нет способа увидеть локальный стек и то, что уже было спарено, таким образом я могу прочитать, какой последовательный порт ему уже назначен, и автоматически открыть объект SerialPort для пользователя.

1 Ответ

2 голосов
/ 28 июня 2011

Ответ: вы не можете или не можете ... вместо этого вы используете Microsoft Bluetooth.Загрузите его для Windows Mobile Bluetooth на устройстве Motorola ... может работать и на других устройствах.Вы можете получить из мобильных образцов, я нашел его здесь на моем жестком диске ... C: \ Program Files (x86) \ Windows Mobile 6 SDK \ Samples \ Common \ CS \ Bluetooth.Затем я добавил это в свой проект, и все, что мне нужно было сделать, это добавить все подключенные устройства в список ListBox

BluetoothRadio radio = new BluetoothRadio();
listBox1.DataSource = radio.PairedDevices;
listBox1.DisplayMember = "Name";

. И затем, когда одно из них было выбрано, вы можете получить к нему доступ как к устройству BlueTooth, например так:

BluetoothDevice device = listBox1.SelectedItem as BluetoothDevice;

Затем вы запускаете поток с помощью

    if (device != null) {
         BTConnectionManager.Instance.startThread(
                    StandardServices.SerialPortServiceGuid,
                    new ThreadStart(StreamProcessor));

    if (BTConnectionManager.Instance.Connect(device)) { 
        ...Do something...

Мне пришлось немного изменить StreamProcessor и BTConnectionManager, чтобы работать для меня, но вот моя версия без ссылок на формы в нем,

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using Microsoft.WindowsMobile.SharedSource.Bluetooth;

namespace Project2 {
/// <summary>
/// Connection Manager to marshal the data connection and reference the
/// data streams to push/pull data.
/// </summary>
public class BTConnectionManager {
    BTConnectionManager() { }

    /// <summary>
    /// reference the Singleton and make a singleton object out of
    /// this since we only want one for now.
    /// </summary>
    public static BTConnectionManager Instance {
        get {
            return Nested.instance;
        }
    }

    /// <summary>
    /// easiest way to make this a singleton that is thread safe.
    /// </summary>
    class Nested {
        static Nested() { }
        internal static readonly BTConnectionManager instance = new BTConnectionManager();
    }

    /// <summary>
    /// The Bluetooth radio.
    /// </summary>
    private BluetoothRadio radio = new BluetoothRadio();


    /// <summary>
    /// Guid of the Bluetooth service
    /// </summary>
    private Guid guid;

    /// <summary>
    /// Thread function that processes data from the stream.
    /// </summary>
    private ThreadStart streamProcessor;

    /// <summary>
    /// The two-way communication stream to the other Bluetooth device.
    /// </summary>
    private NetworkStream stream;

    /// <summary>
    /// A BinaryReader on top of this.stream
    /// </summary>
    private BinaryReader reader;

    /// <summary>
    /// A BinaryWriter on top of this.stream
    /// </summary>
    private BinaryWriter writer;

    /// <summary>
    /// Should we stop the service thread, in preparation for 
    /// exiting the app?
    /// </summary>
    private bool exiting = false;

    /// <summary>
    /// The Bluetooth service.
    /// </summary>
    private BluetoothService bluetoothService;

    /// <summary>
    /// A BinaryWriter used to write to the other Bluetooth device.
    /// </summary>
    public BinaryWriter Writer {
        get { return writer; }
    }

    /// <summary>
    /// A BinaryReader used to read from the other Bluetooth device.
    /// </summary>
    public BinaryReader Reader {
        get { return reader; }
    }

    /// <summary>
    /// Gets a value indicating whether a connection is established with 
    /// the other Bluetooth device.
    /// </summary>
    public bool Connected {
        get { return stream != null; }
    }


    /// <summary>
    /// The two-way communication stream to the other Bluetooth device.
    /// </summary>
    private NetworkStream Stream {
        get { return stream; }
        set {
            stream = value;
            if (stream == null) {
                if (writer != null) {
                    writer.Close();
                    writer = null;
                }
                if (reader != null) {
                    reader.Close();
                    reader = null;
                }
            } else {
                writer = new BinaryWriter(stream);
                reader = new BinaryReader(stream);
            }
        }
    }


    /// <summary>
    /// Creates a new instance of a ConnectionManager.
    /// </summary>
    /// <param name="guid">The Bluetooth service guid.</param>
    /// <param name="streamProcessor">A callback function that will read and process data from the stream.</param>
    public void startThread(Guid guid, ThreadStart dataProcessor) {
        this.guid = guid;
        this.streamProcessor = dataProcessor;
        Thread t = new Thread(new ThreadStart(ServiceThread));
        t.Start();
    }



    /// <summary>
    /// The thread that listens for Bluetooth connections, and processes
    /// the data read from a connection once established.
    /// </summary>
    private void ServiceThread() {
        bluetoothService = new BluetoothService(this.guid);

        while (!exiting) {
            if (!bluetoothService.Started) {
                bluetoothService.Start();
            }
            try {
                this.Stream = bluetoothService.AcceptConnection();
            } catch (System.Net.Sockets.SocketException) {
                // bluetoothService.Stop() was called.  
                // Treat this like a graceful return from AcceptConnection().
            }
            if (!exiting) {
                // Call the streamProcessor to handle the data from the stream.
                streamProcessor();
            }
        }
        exiting = false;

    }

    /// <summary>
    /// Force the service thread to exit.
    /// </summary>
    public void Exit() {
        // This will cause us to fall out of the ServiceThread() loop.
        exiting = true;

        if (!Connected) {
            // We must be waiting on AcceptConnection(), so we need to
            // force an exception to break out.
            bluetoothService.Stop();
        }
    }


    /// <summary>
    /// Connect to another Bluetooth device.
    /// </summary>
    public bool Connect(BluetoothDevice device) {
        if (device != null) {
            try {
                this.Stream = device.Connect(this.guid);
            } catch (System.Net.Sockets.SocketException) {
                // Couldn't connect.
            }

            if (this.Stream == null) {
                System.Windows.Forms.MessageBox.Show("Could not connect to device " + device.Name);
                return false;
            } else {
                // Forcibly break out of the AcceptConnection in 
                // ServiceThread(), and continue on to streamProcessor().
                bluetoothService.Stop();
                return true;
            }
        }
        return false;
    }

    /// <summary>
    /// Disconnect from the other Bluetooth device.
    /// </summary>
    public void Disconnect() {
        Stream = null;
    }



    internal void Disconnect(BluetoothDevice device) {
        Disconnect();
    }
}
}
...