QT上蓝牙编写例子,关于低功耗蓝牙相关类的介绍

这个是关于PC端蓝牙类介绍:http://blog.sina.com.cn/s/blog_8ea72eaa0102wzsd.html

QLowEnergyController

Detailed Description

The QLowEnergyController class provides access to Bluetooth Low Energy Devices.[QLowEnergyController类提供对蓝牙低能耗设备的访问。]

QLowEnergyController acts as the entry point for Bluetooth Low Energy development.[QLowEnergyController是蓝牙低能耗开发的切入点。]

Bluetooth Low Energy defines two types of devices; the peripheral and the central. Each role performs a different task. The peripheral device provides data which is utilized by central devices. An example might be a humidity sensor which measures the moisture in a winter garden. A device such as a mobile phone might read the sensor's value and display it to the user in the greater context of all sensors in the same environment. In this case the sensor is the peripheral device and the mobile phone acts as the central device.[蓝牙低能量定义了两种设备;外围和中心。每个角色执行不同的任务。外围设备提供被中心设备利用的数据。例如,湿度传感器可以测量冬季花园的湿度。移动电话之类的设备可以读取传感器的值,并在相同环境中所有传感器的更大范围内将其显示给用户。在这种情况下,传感器是外围设备,移动电话作为中心设备。]

A controller in the central role is created via the createCentral() factory method. Such an object essentially acts as a placeholder towards a remote Low Energy peripheral device, enabling features such as service discovery and state tracking.[中心角色中的控制器是通过createCentral()工厂方法创建的。此类对象本质上充当远程低能耗外围设备的占位符,支持服务发现和状态跟踪等功能。]

After having created a controller object in the central role, the first step is to establish a connection via connectToDevice(). Once the connection has been established, the controller's state() changes to QLowEnergyController::ConnectedState and the connected() signal is emitted. It is important to mention that some platforms such as a BlueZ based Linux cannot maintain two connected instances of QLowEnergyController to the same remote device. In such cases the second call to connectToDevice() may fail. This limitation may disappear at some stage in the future. The disconnectFromDevice() function is used to break the existing connection.[在中心角色中创建控制器对象之后,第一步是通过connectToDevice()建立连接。一旦建立了连接,控制器的state()将更改为QLowEnergyController::ConnectedState,并发出connected()信号。需要指出的是,有些平台(如基于BlueZ的Linux)无法将QLowEnergyController的两个连接实例维护到同一个远程设备。在这种情况下,对connectToDevice()的第二次调用可能会失败。这种限制可能在未来的某个阶段消失。disconnectFromDevice()函数]

The second step after establishing the connection is to discover the services offered by the remote peripheral device. This process is started via discoverServices() and has finished once the discoveryFinished() signal has been emitted. The discovered services can be enumerated via services().[建立连接后的第二步是发现远程外围设备提供的服务。此过程通过discoverServices()启动,并在发出discoveryFinished()信号后完成。发现的服务可以通过services()进行枚举。]

The last step is to create service objects. The createServiceObject() function acts as factory for each service object and expects the service UUID as parameter. The calling context should take ownership of the returned QLowEnergyService instance.[最后一步是创建服务对象。createServiceObject()函数充当每个服务对象的工厂,并期望服务UUID作为参数。调用上下文应该拥有返回的QLowEnergyService实例。]

Any QLowEnergyService, QLowEnergyCharacteristic or QLowEnergyDescriptor instance which is later created from this controller's connection becomes invalid as soon as the controller disconnects from the remote Bluetooth Low Energy device.[任何QLowEnergyService、QLowEnergyCharacteristic或QLowEnergyDescriptor实例,一旦控制器断开与远程蓝牙低能设备的连接,随后从控制器的连接中创建的实例将无效。]

A controller in the peripheral role is created via the createPeripheral() factory method. Such an object acts as a peripheral device itself, enabling features such as advertising services and allowing clients to get notified about changes to characteristic values.[外围角色的控制器是通过createPeripheral()工厂方法创建的。这样的对象充当外围设备本身,支持广告服务等功能,并允许客户端获得关于特征值更改的通知。]

After having created a controller object in the peripheral role, the first step is to populate the set of GATT services offered to client devices via calls to addService(). Afterwards, one would call startAdvertising() to let the device broadcast some data and, depending on the type of advertising being done, also listen for incoming connections from GATT clients.[在以外围角色创建控制器对象之后,第一步是通过调用addService()来填充向客户端设备提供的一组GATT服务。之后,可以调用startAdvertising()让设备广播一些数据,根据所做广告的类型,还可以监听来自GATT客户端的连接。]

QLowEnergyService

The QLowEnergyService class represents an individual service on a Bluetooth Low Energy Device.[QLowEnergyService类表示蓝牙低能耗设备上的单个服务。]

QLowEnergyService provides access to the details of Bluetooth Low Energy services. The class facilitates the discovery and publification of service details, permits reading and writing of the contained data and notifies about data changes.[QLowEnergyService提供蓝牙低能耗服务的详细信息。该类促进服务细节的发现和公开,允许读取和写入包含的数据,并通知数据更改。]

Service Structure

A Bluetooth Low Energy peripheral device can contain multiple services. In turn each service may include further services. This class represents a single service of the peripheral device and is created via QLowEnergyController::createServiceObject(). The type() indicates whether this service is a primary (top-level) service or whether the service is part of another service. Each service may contain one or more characteristics and each characteristic may contain descriptors. The resulting structure may look like the following diagram[蓝牙低功耗外围设备可以包含多个服务。反过来,每个服务可以包括进一步的服务。该类表示外围设备的单个服务,通过QLowEnergyController::createServiceObject()创建。type()指示该服务是主服务(顶级服务)还是另一个服务的一部分。每个服务可以包含一个或多个特征,每个特征可以包含描述符。得到的结构可能如下图所示]:

 

 

A characteristic is the principle information carrier. It has a value() and properties() describing the access permissions for the value. The general purpose of the contained descriptor is to further define the nature of the characteristic. For example, it might specify how the value is meant to be interpreted or whether it can notify the value consumer about value changes.[特征是信息的主要载体。它有一个值()和属性()来描述该值的访问权限。所包含描述符的一般用途是进一步定义特征的性质。例如,它可以指定如何解释值,或者是否可以将值的变化通知值消费者。]

Service Interaction

Once a service object was created for the first time, its details are yet to be discovered. This is indicated by its current state() being DiscoveryRequired. It is only possible to retrieve the serviceUuid() and serviceName().[一旦第一次创建了服务对象,它的细节还没有被发现。它的当前状态()是必需的。只能检索serviceUuid()和serviceName()。]

The discovery of its included services, characteristics and descriptors is triggered when calling discoverDetails(). During the discovery the state() transitions from DiscoveryRequired via DiscoveringServices to its final ServiceDiscovered state. This transition is advertised via the stateChanged() signal. Once the details are known, all of the contained characteristics, descriptors and included services are known and can be read or written.[当调用discoverDetails()时,将触发其包含的服务、特征和描述符的发现。在发现过程中,state()从DiscoveryRequired(通过DiscoveringServices)转换到最后的ServiceDiscovered状态。这个转换是通过stateChanged()信号来通知的。一旦知道了细节,所有包含的特征、描述符和包含的服务都是已知的,可以读写。]

The values of characteristics and descriptors can be retrieved via QLowEnergyCharacteristic and QLowEnergyDescriptor, respectively. However, direct reading or writing of these attributes requires the service object. The readCharacteristic() function attempts to re-read the value of a characteristic. Although the initial service discovery may have obtained a value already this call may be required in cases where the characteristic value constantly changes without any notifications being provided. An example might be a time characteristic that provides a continuous value.[特征和描述符的值可以分别通过QLowEnergyCharacteristic和QLowEnergyDescriptor来检索。但是,直接读写这些属性需要服务对象。函数的作用是:重新读取一个特征值。尽管初始服务发现可能已经获得了一个值,但是在特征值不断变化而不提供任何通知的情况下,可能需要调用这个值。一个例子可能是提供连续值的时间特征。] 

If the read attempt is successful, the characteristicRead() signal is emitted. A failure to read the value triggers the CharacteristicReadError. The writeCharacteristic() function attempts to write a new value to the given characteristic. If the write attempt is successful, the characteristicWritten() signal is emitted. A failure to write triggers the CharacteristicWriteError. Reading and writing of descriptors follows the same pattern.[如果读取尝试成功,则发出characteristicRead()信号。读取值失败将触发CharacteristicReadError。函数的作用是:为给定的特征写一个新值。如果写入尝试成功,则发出characteristicWritten()信号。写入失败将触发CharacteristicWriteError。描述符的读写遵循相同的模式。]

Every attempt is made to read or write the value of a descriptor or characteristic on the hardware. This means that meta information such as QLowEnergyCharacteristic::properties() is generally ignored when reading and writing. As an example, it is possible to call writeCharacteristic() despite the characteristic being read-only based on its meta data description.[每次尝试都是在硬件上读写描述符或特征的值。这意味着像QLowEnergyCharacteristic::properties()这样的元信息在读写时通常会被忽略。例如,可以调用writeCharacteristic(),尽管基于其元数据描述的特性是只读的。]

The resulting write request is forwarded to the connected device and it is up to the device to respond to the potentially invalid request. In this case the result is the emission of the CharacteristicWriteError in response to the returned device error. [产生的写请求被转发给连接的设备,由设备响应可能无效的请求。在这种情况下,结果是发射CharacteristicWriteError来响应返回的设备错误。]

This behavior simplifies interaction with devices which report wrong meta information. If it was not possible to forward the request to the remote device the OperationError is set. A potential reason could be that the to-be-written characteristic object does not even belong the current service. In summary, the two types of errors permit a quick distinction of local and remote error cases.[这种行为简化了与报告错误元信息的设备的交互。如果无法将请求转发给远程设备,则设置操作错误。一个潜在的原因可能是要写入的特征对象甚至不属于当前服务。总之,这两种类型的错误允许快速区分本地错误和远程错误。]

All requests are serialised based on First-In First-Out principle. For example, issuing a second write request, before the previous write request has finished, is delayed until the first write request has finished.[所有的请求都是基于先进先出原则序列化的。例如,在前一个写请求完成之前发出第二个写请求将被延迟到第一个写请求完成之后。]

In some cases the peripheral generates value updates which the central is interested in receiving. In order for a characteristic to support such notifications it must have the QLowEnergyCharacteristic::Notify or QLowEnergyCharacteristic::Indicate property and a descriptor of type QBluetoothUuid::ClientCharacteristicConfiguration. Provided those conditions are fulfilled notifications can be enabled as shown in the following code segment:[在某些情况下,外围设备会生成中心感兴趣的值更新。为了使一个特性支持这样的通知,它必须具有QLowEnergyCharacteristic::Notify或QLowEnergyCharacteristic::Indicate property和q蓝牙thuuid::ClientCharacteristicConfiguration类型的描述符。如果满足了这些条件,通知可以启用,如下面的代码段所示:]

//PreCondition: service details already discovered
      QLowEnergyCharacteristic batteryLevel = service->characteristic(
                  QBluetoothUuid::BatteryLevel);
      if (!batteryLevel.isValid())
          return;

      QLowEnergyDescriptor notification = batteryLevel.descriptor(
                  QBluetoothUuid::ClientCharacteristicConfiguration);
      if (!notification.isValid())
          return;

      // establish hook into notifications
      connect(service, SIGNAL(characteristicChanged(QLowEnergyCharacteristic,QByteArray)),
              this, SLOT(characteristicChanged(QLowEnergyCharacteristic,QByteArray)));

      // enable notification
      service->writeDescriptor(notification, QByteArray::fromHex("0100"));

      // disable notification
      //service->writeDescriptor(notification, QByteArray::fromHex("0000"));

      // wait until descriptorWritten() signal is emitted
      // to confirm successful write

The example shows a battery level characteristic which updates the central on every value change. The notifications are provided via the characteristicChanged() signal. More details about this mechanism are provided by the Bluetooth Specification.

[这个例子显示了一个电池电量特性,它可以在每次值改变时更新中心。通知是通过characteristicChanged()信号提供的。关于此机制的更多细节由蓝牙规范提供。]

Service Data Sharing

Each QLowEnergyService instance shares its internal states and information with other QLowEnergyService instance of the same service. If one instance initiates the discovery of the service details, all remaining instances automatically follow. Therefore the following snippet always works:[每个QLowEnergyService实例与相同服务的其他QLowEnergyService实例共享其内部状态和信息。如果一个实例启动了服务细节的发现,那么所有剩余的实例都会自动跟随。因此,以下代码片段总是有效的:]

 QLowEnergyService *first, *second;
      QLowEnergyController control(remoteDevice);
      control.connectToDevice();

      // waiting for connection

      first = control.createServiceObject(QBluetoothUuid::BatteryService);
      second = control.createServiceObject(QBluetoothUuid::BatteryService);
      Q_ASSERT(first->state() == QLowEnergyService::DiscoveryRequired);
      Q_ASSERT(first->state() == second->state());

      first->discoverDetails();

      Q_ASSERT(first->state() == QLowEnergyService::DiscoveringServices);
      Q_ASSERT(first->state() == second->state());

Other operations such as calls to readCharacteristic(), readDescriptor(), writeCharacteristic(), writeDescriptor() or the invalidation of the service due to the related QLowEnergyController disconnecting from the device are shared the same way.[其他操作,例如对readCharacteristic()、readDescriptor()、writeCharacteristic()、writeDescriptor()的调用,或者由于相关的QLowEnergyController从设备断开而导致的服务失效,都是以相同的方式共享的]

QLowEnergyCharacteristic

The QLowEnergyCharacteristic class stores information about a Bluetooth Low Energy service characteristic.[QLowEnergyCharacteristic类存储关于蓝牙低能耗服务特性的信息。]

QLowEnergyCharacteristic provides information about a Bluetooth Low Energy service characteristic's name(), uuid(), value(), properties(), handle() and descriptors(). To obtain the characteristic's specification and information, it is necessary to connect to the device using the QLowEnergyService and QLowEnergyController classes.[QLowEnergyCharacteristic提供有关蓝牙低能耗服务特性的名称()、uuid()、值()、属性()、句柄()和描述符()的信息。为了获得特性的规范和信息,需要使用QLowEnergyService和QLowEnergyController类连接到设备。]

The characteristic value may be written via the QLowEnergyService instance that manages the service to which this characteristic belongs. The QLowEnergyService::writeCharacteristic() function writes the new value. The QLowEnergyService::characteristicWritten() signal is emitted upon success. The value() of this object is automatically updated accordingly.[特征值可以通过管理该特征所属的服务的QLowEnergyService实例写入。函数的作用是:写入新值。QLowEnergyService:: characteristicwrite()信号在成功时发出。此对象的值()将相应地自动更新。]

Characteristics may contain none, one or more descriptors. They can be individually retrieved using the descriptor() function. The descriptors() function returns all descriptors as a list. The general purpose of a descriptor is to add contextual information to the characteristic. For example, the descriptor might provide format or range information specifying how the characteristic's value is to be interpreted.[特征可以不包含任何、一个或多个描述符。可以使用descriptor()函数分别检索它们。函数的作用是:以列表的形式返回所有的描述符。描述符的一般用途是向特征中添加上下文信息。例如,描述符可能提供指定如何解释特征值的格式或范围信息。]

QLowEnergyDescriptor

The QLowEnergyDescriptor class stores information about the Bluetooth Low Energy descriptor.[QLowEnergyDescriptor类存储关于蓝牙低能量描述符的信息。]

QLowEnergyDescriptor provides information about a Bluetooth Low Energy descriptor's name(), uuid(), value() and handle(). Descriptors are encapsulated by Bluetooth Low Energy characteristics and provide additional centextual information about the characteristic (data format, notification activation and so on).[QLowEnergyDescriptor提供了关于蓝牙低功耗描述符的名称()、uuid()、值()和句柄()的信息。描述符由蓝牙低能量特性封装,并提供关于该特性的附加虚拟信息(数据格式、通知激活等)。]

The descriptor value may be written via the QLowEnergyService instance that manages the service to which this descriptor belongs. The QLowEnergyService::writeDescriptor() function writes the new value. The QLowEnergyService::descriptorWritten() signal is emitted upon success. The cahced value() of this object is updated accordingly.[描述符值可以通过管理该描述符所属服务的QLowEnergyService实例来写入。函数的作用是:写入新值。成功时发出QLowEnergyService::descriptorWritten()信号。此对象的cahced值()将相应地更新。]

QLowEnergyDescriptorData

The QLowEnergyDescriptorData class is used to create GATT service data.[QLowEnergyDescriptorData类用于创建GATT服务数据。]

An object of this class provides a descriptor to be added to a QLowEnergyCharacteristicData object via QLowEnergyCharacteristicData::addDescriptor().[这个类的对象提供了一个描述符,可以通过QLowEnergyCharacteristicData::addDescriptor()将其添加到QLowEnergyCharacteristicData对象中。]

Note: The member functions related to access permissions are only applicable to those types of descriptors for which the Bluetooth specification does not prescribe if and how their values can be accessed.[注意:与访问权限相关的成员函数仅适用于蓝牙规范没有规定是否以及如何访问其值的描述符类型。]

 

阅读上面的内容,按照里面的步骤进行编写程序,就能够写出在手机上运行的蓝牙客户机程序。

  • 1
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值