Что такое windows server bluetooth

Сервер Bluetooth GATT Bluetooth GATT Server

В этой статье описываются API-интерфейсы сервера Bluetooth Generic Attribute (GATT) для приложений универсальной платформы Windows (UWP) и приводится пример кода для основных задач сервера GATT. This article demonstrates Bluetooth Generic Attribute (GATT) Server APIs for Universal Windows Platform (UWP) apps, along with sample code for common GATT server tasks:

  • Определение поддерживаемых служб Define the supported services
  • Публикация сервера (необходима для того, чтобы удаленные клиенты могли обнаружить этот сервер) Publish server so it can be discovered by remote clients
  • Объявление поддержки для службы Advertise support for service
  • Реагирование на запросы чтения и записи Respond to read and write requests
  • Отправка уведомлений подписанным клиентам Send notifications to subscribed clients

В Package. appxmanifestнеобходимо объявить возможность «Bluetooth». You must declare the «bluetooth» capability in Package.appxmanifest.

Важные API Important APIs

Обзор Overview

Как правило, Windows функционирует в роли клиента. Windows usually operates in the client role. Однако существует множество сценариев, когда операционная система Windows должна выполнять функции сервера Bluetooth GATT с низким энергопотреблением. Nevertheless, many scenarios arise which require Windows to act as a Bluetooth LE GATT Server as well. Сюда относятся почти все сценарии для устройств интернета вещей, а также большинство сценариев обмена данными с использованием BLE. Все эти сценарии требуют, чтобы операционная система Windows функционировала как сервер GATT. Almost all the scenarios for IoT devices, along with most cross-platform BLE communication will require Windows to be a GATT Server. Кроме того, эта технология обязательна для такого популярного сценария, как отправка уведомлений на ближайшие носимые устройства. Additionally, sending notifications to nearby wearable devices has become a popular scenario that requires this technology as well.

Операции сервера связаны с классами Service Provider и GattLocalCharacteristic. Server operations will revolve around the Service Provider and the GattLocalCharacteristic. Эти два класса предоставляют функции, необходимые для объявления, реализации и предоставления иерархии данных на удаленном устройстве. These two classes will provide the functionality needed to declare, implement and expose a hierarchy of data to a remote device.

Определение поддерживаемых служб Define the supported services

Приложение может объявить одну или несколько служб, которые будут опубликованы в Windows. Your app may declare one or more services that will be published by Windows. Каждая служба имеет уникальный идентификатор UUID. Each service is uniquely identified by a UUID.

Атрибуты и идентификаторы UUID Attributes and UUIDs

Каждая служба, характеристика и дескриптор имеет свой уникальный 128-битный идентификатор UUID. Each service, characteristic and descriptor is defined by it’s own unique 128-bit UUID.

Ко всем API-интерфейсам Windows применяется термин GUID, но в стандарте Bluetooth этот идентификатор определяется как UUID. The Windows APIs all use the term GUID, but the Bluetooth standard defines these as UUIDs. В нашем случае эти два термина взаимозаменяемы, поэтому мы будем использовать термин UUID. For our purposes, these two terms are interchangeable so we’ll continue to use the term UUID.

Если атрибут является стандартным и определяется с помощью определяемого пользователем протокола Bluetooth, он также будет иметь соответствующий 16-разрядный короткий идентификатор (например, UUID уровня аккумулятора — 00002A19-0000-1000-8000-00805F9B34FB, а короткий идентификатор — 0x2A19). If the attribute is standard and defined by the Bluetooth SIG-defined, it will also have a corresponding 16-bit short ID (for example, Battery Level UUID is 00002A19-0000-1000-8000-00805F9B34FB and the short ID is 0x2A19). Эти стандартные идентификаторы UUID описаны в статьях GattServiceUuids и GattCharacteristicUuids. These standard UUIDs can be seen in GattServiceUuids and GattCharacteristicUuids.

Читайте также:  Как узнать конфигурацию ноутбука windows

Если ваше приложение реализует собственную службу, необходимо создать пользовательский UUID. If your app is implementing it’s own custom service, a custom UUID will have to be generated. Это легко сделать в Visual Studio с помощью команды Tools (Инструменты) -> CreateGuid (используйте вариант 5, чтобы получить идентификатор в формате «xxxxxxxx-xxxx-. xxxx»). This is easily done in Visual Studio through Tools -> CreateGuid (use option 5 to get it in the «xxxxxxxx-xxxx-. xxxx» format). Этот UUID можно использовать для объявления новых локальных служб, характеристик или дескрипторов. This uuid can now be used to declare new local services, characteristics or descriptors.

Службы с ограниченным доступом Restricted Services

Перечисленные ниже службы зарезервированы системой и в настоящее время недоступны для публикации: The following Services are reserved by the system and cannot be published at this time:

  1. Device Information Service (DIS) Device Information Service (DIS)
  2. Generic Attribute Profile Service (GATT) Generic Attribute Profile Service (GATT)
  3. Generic Access Profile Service (GAP) Generic Access Profile Service (GAP)
  4. Human Interface Device Service (HOGP) Human Interface Device Service (HOGP)
  5. Scan Parameters Service (SCP) Scan Parameters Service (SCP)

При попытке создать заблокированную службу вызов к CreateAsync вернет ошибку BluetoothError.DisabledByPolicy. Attempting to create a blocked service will result in BluetoothError.DisabledByPolicy being returned from the call to CreateAsync.

Генерируемые атрибуты Generated Attributes

Перечисленные ниже дескрипторы автоматически генерируются системой в соответствии с классом GattLocalCharacteristicParameters, предоставленным в процессе создания характеристики: The following descriptors are autogenerated by the system, based on the GattLocalCharacteristicParameters provided during creation of the characteristic:

  1. Client Characteristic Configuration (если характеристика имеет маркер indicatable или notifiable) Client Characteristic Configuration (if the characteristic is marked as indicatable or notifiable).
  2. Characteristic User Description (если задано свойство UserDescription) Characteristic User Description (if UserDescription property is set). Для получения дополнительных сведений см. свойство GattLocalCharacteristicParameters.UserDescription. See GattLocalCharacteristicParameters.UserDescription property for more info.
  3. Characteristic Format (по одному дескриптору на каждый указанный формат представления) Characteristic Format (one descriptor for each presentation format specified). Для получения дополнительных сведений см. свойство GattLocalCharacteristicParameters.PresentationFormats. See GattLocalCharacteristicParameters.PresentationFormats property for more info.
  4. Characteristic Aggregate Format (если указано несколько форматов представления) Characteristic Aggregate Format (if more than one presentation format is specified). Для получения дополнительных сведений см. свойство GattLocalCharacteristicParameters.PresentationFormats. GattLocalCharacteristicParameters.See PresentationFormats property for more info.
  5. Characteristic Extended Properties (если характеристика помечена битом расширенных свойств) Characteristic Extended Properties (if the characteristic is marked with the extended properties bit).

Значение дескриптора Extended Properties определяется свойствами характеристики ReliableWrites и WritableAuxiliaries. The value of the Extended Properties descriptor is determined via the ReliableWrites and WritableAuxiliaries characteristic properties.

Попытка создать зарезервированный дескриптор вызывает исключение. Attempting to create a reserved descriptor will result in an exception.

Примечание: широковещательная рассылка в настоящее время не поддерживается. Note that broadcast is not supported at this time. Если задать свойство Broadcast GattCharacteristicProperty, будет создано исключение. Specifying the Broadcast GattCharacteristicProperty will result in an exception.

Создание иерархии служб и характеристик Build up the hierarchy of services and characteristics

Для создания и объявления определения основной корневой службы используется класс GattServiceProvider. The GattServiceProvider is used to create and advertise the root primary service definition. Каждой службе требуется собственный объект ServiceProvider, в который передается GUID: Each service requires it’s own ServiceProvider object that takes in a GUID:

Основные службы находятся на верхнем уровне дерева GATT. Primary services are the top level of the GATT tree. Основные службы содержат характеристики и другие службы («включенные» или дополнительные). Primary services contain characteristics as well as other services (called ‘Included’ or secondary services).

Задайте обязательные характеристики и дескрипторы для службы: Now, populate the service with the required characteristics and descriptors:

Читайте также:  Windows find command line options

Здесь также удобно объявлять обработчики событий для операций, поддерживаемых каждой характеристикой (см. рис. выше). As shown above, this is also a good place to declare event handlers for the operations each characteristic supports. Чтобы приложение правильно реагировало на запросы, необходимо определить и настроить обработчик событий для каждого типа запроса, поддерживаемого атрибутом. To respond to requests correctly, an app must defined and set an event handler for each request type the attribute supports. Если обработчик не зарегистрирован, система мгновенно выполняет запрос с ошибкой UnlikelyError. Failing to register a handler will result in the request being completed immediately with UnlikelyError by the system.

Постоянные характеристики Constant characteristics

Некоторые значения характеристик не меняются в течение всего жизненного цикла приложения. Sometimes, there are characteristic values that will not change during the course of the app’s lifetime. В этом случае рекомендуется объявить постоянную характеристику во избежание нежелательной активации приложения: In that case, it is advisable to declare a constant characteristic to prevent unnecessary app activation:

Публикация службы Publish the service

После определения всех атрибутов службы необходимо опубликовать поддержку для этой службы. Once the service has been fully defined, the next step is to publish support for the service. Публикация информирует операционную систему о том, что эта служба должна возвращаться, когда удаленные устройства выполняют поиск служб. This informs the OS that the service should be returned when remote devices perform a service discovery. Необходимо настроить два свойства: IsDiscoverable и IsConnectable. You will have to set two properties — IsDiscoverable and IsConnectable:

  • IsDiscoverable: объявляет удаленным устройствам понятное имя, чтобы они могли обнаружить текущее устройство. IsDiscoverable: Advertises the friendly name to remote devices in the advertisement, making the device discoverable.
  • IsConnectable: публикует подключаемое объявление, используемое в периферийной роли. IsConnectable: Advertises a connectable advertisement for use in peripheral role.

Когда для службы заданы оба свойства, Discoverable и Connectable, система добавляет UUID этой службы в пакет объявления. When a service is both Discoverable and Connectable, the system will add the Service Uuid to the advertisement packet. Размер пакета объявления составляет всего 31 байт, и 16 из них занимает 128-битный UUID. There are only 31 bytes in the Advertisement packet and a 128-bit UUID takes up 16 of them!

Примечание: когда служба публикуется на переднем плане и работа приложения приостанавливается, приложение должно вызвать функцию StopAdvertising. Note that when a service is published in the foreground, an application must call StopAdvertising when the application suspends.

Реагирование на запросы чтения и записи Respond to Read and Write requests

Как упоминалось в разделе об объявлении требуемых характеристик, атрибут GattLocalCharacteristics поддерживает 3 типа событий: ReadRequested, WriteRequested и SubscribedClientsChanged. As we saw above while declaring the required characteristics, GattLocalCharacteristics have 3 types of events — ReadRequested, WriteRequested and SubscribedClientsChanged.

Читайте также:  Ошибка при поиске обновлений windows 80072efe

Чтение Read

Когда удаленное устройство пытается прочитать значение характеристики и это значение не является постоянным, вызывается событие ReadRequested. When a remote device tries to read a value from a characteristic (and it’s not a constant value), the ReadRequested event is called. Характеристика, для которой была вызвана операция чтения, а также аргументы, содержащие сведения об удаленном устройстве, передаются делегату: The characteristic the read was called on as well as args (containing information about the remote device) is passed to the delegate:

Write Write

Когда удаленное устройство пытается записать значение в характеристику, вызывается событие WriteRequested с подробными сведениями об удаленном устройстве, соответствующей характеристике и самом значении: When a remote device tries to write a value to a characteristic, the WriteRequested event is called with details about the remote device, which characteristic to write to and the value itself:

Существует 2 типа операций записи: с ответом и без ответа. There are 2 types of Writes — with and without response. Чтобы определить, какую операцию записи выполняет удаленное устройство, используйте свойство GattWriteOption в объекте GattWriteRequest. Use GattWriteOption (a property on the GattWriteRequest object) to figure out which type of write the remote device is performing.

Отправка уведомлений подписанным клиентам Send notifications to subscribed clients

Отправка уведомлений — наиболее часто выполняемая операция сервера GATT. Уведомления выполняют важную функцию публикации данных на удаленных устройствах. The most frequent of the GATT Server operations, notifications perform the critical function of pushing data to the remote devices. В зависимости от конкретной ситуации можно отправлять уведомления всем подписанным клиентам или самостоятельно выбирать устройства для отправки нового значения: Sometimes, you’ll want to notify all subscribed clients but othertimes you may want to pick which devices to send the new value to:

Когда новое устройство подписывается на уведомления, вызывается событие SubscribedClientsChanged: When a new device subscribes for notifications, the SubscribedClientsChanged event gets called:

Примечание: приложение может определять максимальный размер уведомления для конкретных клиентов с помощью свойства MaxNotificationSize. Note that an application can get the maximum notification size for a particular client with the MaxNotificationSize property. Система применяет усечение к любым данным, размер которых превышает максимальное значение. Any data larger than the maximum size will be truncated by the system.

Оцените статью