32feet.net, как обнаружить асинхронные устройства Bluetooth в c # - PullRequest
3 голосов
/ 15 октября 2011

Я пытаюсь использовать библиотеку bluetooth 32feet.NET в приложении C # для обнаружения соседних устройств.Цель моего маленького приложения - сообщить ПК, кто находится в комнате, с помощью функции bluetooth мобильных телефонов людей.

Лучший способ сделать что-то подобное - это позволить устройствам, которые я хочу, "«трек» подключите один раз, затем постоянно проверяйте, можно ли их обнаружить через блютус.

Теперь мои вопросы:

  1. Нужно ли связывать или аутентифицировать устройство с моим приложением?Как сделать это в C # с 32feet.NET?

  2. Как постоянно проверять наличие устройств в радиусе действия и сравнивать их с сохраненными устройствами?

Я знаю, что все это, вероятно, находится в документации библиотеки, но мне действительно трудно читать, и большинство примеров, похоже, написаны на VB, который я не знаю, и который трудно перевести на C # (особенно когда это происходит)к AsyncCallbacks и т. п.).

Я был бы очень рад, если бы кто-нибудь дал мне толчок в правильном направлении!

Ответы [ 2 ]

8 голосов
/ 15 октября 2011

Несколько предостережений, я предполагаю, что вы не имеете дело с HID-устройствами, они обычно обрабатываются ОС. Я также только начал использовать 32feet, и я использую его для создания соединений со службой последовательного порта на сканерах штрих-кодов Bluetooth, так что могут быть более эффективные способы для ваших нужд, но это может указать вам верное направление для начала .

Вам необходимо выполнить сопряжение устройства, да. Если вы используете его в приложении WinForms, на самом деле вы можете отобразить форму, которая обрабатывает сканирование устройств и позволяет выбрать одно из них, например:

bool PairDevice()
{
    using (var discoverForm = new SelectBluetoothDeviceDialog())
    {
        if (discoverForm.ShowDialog(this) != DialogResult.OK)
        {
            // no device selected
            return false;
        }

        BluetoothDeviceInfo deviceInfo = discoverForm.SelectedDevice;

        if (!deviceInfo.Authenticated) // previously paired?
        {
            // TODO: show a dialog with a PIN/discover the device PIN
            if (!BluetoothSecurity.PairDevice(deviceInfo.DeviceAddress, myPin)) 
            {
                // not previously paired and attempt to pair failed
                return false;
            }
        }

        // device should now be paired with the OS so make a connection to it asynchronously
        var client = new BluetoothClient();
        client.BeginConnect(deviceInfo.DeviceAddress, BluetoothService.SerialPort, this.BluetoothClientConnectCallback, client);

        return true;
    }
}

void BluetoothClientConnectCallback(IAsyncResult result)
{
    var client = (BluetoothClient)result.State;
    client.EndConnect();

    // get the client's stream and do whatever reading/writing you want to do.
    // if you want to maintain the connection then calls to Read() on the client's stream should block when awaiting data from the device

    // when you're done reading/writing and want to close the connection or the device servers the connection control flow will resume here and you need to tidy up
    client.Close();
}

Безусловно, лучший способ, если ваши устройства вещают, что они доступны для соединения, - это установить BluetoothListener, который будет непрерывно прослушивать вещательные устройства, и когда оно будет найдено, вы получите BluetoothClient экземпляр, который вы можете использовать так же, как в первый раз, когда вы создали пару:

void SetupListener()
{
    var listener = new BluetoothListener(BluetoothService.SerialPort);
    listener.Start();
    listener.BeginAcceptBluetoothClient(this.BluetoothListenerAcceptClientCallback, listener);
}


void BluetoothListenerAcceptClientCallback(IAsyncResult result)
{
    var listener = (BluetoothListener)result.State;

    // continue listening for other broadcasting devices
    listener.BeginAcceptBluetoothClient(this.BluetoothListenerAcceptClientCallback, listener);

    // create a connection to the device that's just been found
    BluetoothClient client = listener.EndAcceptBluetoothClient();

    // the method we're in is already asynchronous and it's already connected to the client (via EndAcceptBluetoothClient) so there's no need to call BeginConnect

    // TODO: perform your reading/writing as you did in the first code sample

    client.Close();
}

Менее привлекательный, но полезный, если ваше устройство не транслирует соединения, вы можете создать новый BluetoothClient и попросить вернуть все найденные устройства:

void ScanForBluetoothClients()
{
    var client = new BluetoothClient();
    BluetoothDeviceInfo[] availableDevices = client.DiscoverDevices(); // I've found this to be SLOW!

    foreach (BluetoothDeviceInfo device in availableDevices)
    {
        if (!device.Authenticated)
        {
            continue;
        }

        var peerClient = new BluetoothClient();
        peerClient.BeginConnect(deviceInfo.DeviceAddress, BluetoothService.SerialPort, this.BluetoothClientConnectCallback, peerClient);
    }
}
1 голос
/ 27 октября 2012

Это не ответ, но я не смог разместить столько кода в разделе комментариев.Измените эти строки кода:

//continue listening for other broadcasting devices
listener.BeginAcceptBluetoothClient(this.BluetoothListenerAcceptClientCallback, listener);

// create a connection to the device that's just been found
BluetoothClient client = listener.EndAcceptBluetoothClient();

до

// create a connection to the device that's just been found
BluetoothClient client = listener.EndAcceptBluetoothClient();

// continue listening for other broadcasting devices
listener.BeginAcceptBluetoothClient(this.BluetoothListenerAcceptClientCallback, listener);

В основном, измените последовательность кода .. Как и для каждого вызова метода BeginXXXX должен быть следующий EndXXXX.И весь приведенный выше код, вы пытаетесь BeginAcceptBluetoothClient через уже начался "BeginAcceptBluetoothClient".

Надеюсь, вы понимаете.

...