今天我们介绍蓝牙通信的另一种方式--BLE(Bluetooth Low Energy,蓝牙低功耗)。
什么是BLE
在《无线通信3:HC05/HC06经典蓝牙BT模块》我们提到过经典蓝牙BT和蓝牙低功耗BLE的区别。顾名思义,低功耗蓝牙追求的是极低的功耗,它的主要应用场景是短距离、少数据量的传输场景,不像经典蓝牙那样通信时要一直保持连接,BLE可以只在传输数据时建立连接,空闲时进入睡眠模式来节能,这使BLE通信的功耗可以做的很低,功耗可以是经典蓝牙的百分之一。
BLE不但支持点对点传输,还支持广播模式、还可以组建Mesh网络。
BLE的特性,让它非常适合那些长时间靠电池供电,只偶尔发送少量数据的小设备。比如健康手环、追踪标签、物联网传感器等等。
BLE服务端和客户端
在BLE通信模式中,存在两类设备:BLE服务端(BLE Server)和BLE客户端(BLE Client)。通信时,BLE服务端向外发送信号,可以被附近的BLE客户端发现,一个BLE客户端可以连接特定的服务端,然后读取服务端发送的信号数据。
BLE数据结构:GATT
理解BLE通信还需要几个概念,最重要的就是GATT,GATT全称为Generic Attributes。可以简单地为BLE蓝牙通信的基础数据结构。
BLE Service
GATT结构里最上层的是Profile,一个Profile包含至少一个BLE Service,通常一个BLE设备是包含多个Service的。 这些BLE Service并不是随随便便自己可以设定的,而是由蓝牙技术联盟(Bluetooth Special Interest Group)为了规范而事先统一制定的。比如有显示电量的Service,还有心跳、血压、计重等等各种Service。
BLE Characteristic
每个Service下面包含一个或者多个特征(Characteristic),这些Characteristic包含特征的声明(Declaration)、数据值(Value)和描述符(Descriptor)。这些特征组成可以完整地描述一个Characteristic如何被使用,常见的操作如:
Broadcast
Read
Write without response
Write
Notify
Indicate
Authenticated Signed Writes
Extended Properties
UUID
在BLE GATT中,每个Service、每个Characteristic和每个Descriptor都有一个特定的128比特的UUID表示,就是类似下面的一串数字:
0x0000xxxx-0000-1000-8000-00805F9B34FB
为了简化,蓝牙技术联盟定义了16位UUID代替上面的基本UUID的‘x’部分。例如,心率测量特性使用0X2A37作为它的16位UUID,因此它完整的128位UUID为:
0x00002A37-0000-1000-8000-00805F9B34FB
值得注意的是蓝牙技术联盟所用的基本UUID不能用于任何自定义的属性、服务和特性。另外对于自定义UUID,必须使用另外完整的128位UUID。
如何用Arduino IDE开发BLE应用
在Arduino开发环境里开发BLE应用,我们一般有两种选择:
使用Arduino开发板配合BLE模块,类似经典蓝牙HC05/HC06模块,蓝牙低功耗也有比较流行的HM-10模块,HM-10模块是基于TI的CC2540/CC2541 BLE 4.0模组。Arduino开发板通过串口通信给HM-10发送AT命令来设置参数和收发数据。
使用ESP32这样的自带BLE功能且能用Arduino IDE开发的开发板。ESP32除了自带WiFi,还板载了蓝牙双模(经典蓝牙BT和蓝牙低功耗BLE),体积小价格也香。
如果你选择第一种,网上也有很多关于Arduino配合HM-10模块的使用教程,我们这里就不介绍了。在下面的实践中我们将使用ESP32作为我们的开发平台。
使用ESP32创建BLE Server
在使用ESP32开发板前,我们需要让Arduino IDE支持ESP32开发板,新手可以参考《ESP32-CAM打造低成本网络监控摄像头》一文中的“ 安装ESP32插件”一节。
安装成功后,选择DOIT DEVKIT V1板型,打开Arduino IDE的文件->示例里,我们就可以看到BLE相关的几个例子。我们打开BLE_server或者复制以下代码到IDE里:
/*
Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleServer.cpp
Ported to Arduino ESP32 by Evandro Copercini
updates by chegewara
*/
#include
#include
#include
// See the following for generating UUIDs:
// https://www.uuidgenerator.net/
#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"
void setup() {
Serial.begin(115200);
Serial.println("Starting BLE work!");
BLEDevice::init("MyESP32");
BLEServer *pServer = BLEDevice::createServer();
BLEService *pService = pServer->createService(SERVICE_UUID);
BLECharacteristic *pCharacteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID,
BLECharacteristic::PROPERTY_READ |
BLECharacteristic::PROPERTY_WRITE
);
pCharacteristic->setValue("Hello World says Neil");
pService->start();
// BLEAdvertising *pAdvertising = pServer->getAdvertising(); // this still is working for backward compatibility
BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
pAdvertising->addServiceUUID(SERVICE_UUID);
pAdvertising->setScanResponse(true);
pAdvertising->setMinPreferred(0x06); // functions that help with iPhone connections issue
pAdvertising->setMinPreferred(0x12);
BLEDevice::startAdvertising();
Serial.println("Characteristic defined! Now you can read it in your phone!");
}
void loop() {
// put your main code here, to run repeatedly:
delay(2000);
}
我们来过一遍代码,解释一下:
#include
#include
#include
开头引入一些必要的BLE相关的库文件。
#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"
然后我们需要定义服务(Service),特征(Characteristic)的UUID码,因为这里我们是自定义的服务和特征,所以首先我们不能使用跟蓝牙技术联盟规定重复的UUID,而且我们必须使用完整的128位UUID,为了方便我们可以使用一些在线随机生成UUID的网络服务:
https://www.uuidgenerator.net/
在setup()里,建立串口通信,波特率设为115200。然后首先创建一个BLE设备,在参数里传入设备名,设备名可以随便取。
BLEDevice::init("BLE Device name");
然后我们需要设置设备的模式为BLE Server:
BLEServer *pServer = BLEDevice::createServer();
接下去给这个Server添加一个Service,传入头部设置的Service UUID:
BLEService *pService = pServer->createService(SERVICE_UUID);
再为这个Service创建Characteristic,这里除了传入UUID,还要声明这个Characteristic的读写属性,这个例子里是可读可写:
BLECharacteristic *pCharacteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID,
BLECharacteristic::PROPERTY_READ |
BLECharacteristic::PROPERTY_WRITE
);
然后给Characteristic赋个初始值。这个值可以被客户端读取然后改写。
pCharacteristic->setValue("Hello World says Neil");
最后,我们开启这个Service,然后开始广播。这样这个Server就可以被BLE的客户端扫描到。
BLEAdvertising *pAdvertising = pServer->getAdvertising();
pAdvertising->start();
这样,一个简单的BLE Server就创建成功了,编译上传就可以了,十分简单。
BLE Client端
BLE Server创建完成后,我们需要Client端来连接Server,并读写数据。在BLE应用中,Client端往往是手机,当然也可以是其他单片机。
下面我们就分别演示一下这两种方式。
方式一:单片机
如果使用单片机作为BLE Client,那么同样需要配合BLE模组或者单片机自带BLE功能,这里我们用另外一块ESP32演示。
我们打开Arduino IDE 文件->示例里的BLE_client例子:
/**
* A BLE client example that is rich in capabilities.
*/
#include "BLEDevice.h"
//#include "BLEScan.h"
// The remote service we wish to connect to.
static BLEUUID serviceUUID("4fafc201-1fb5-459e-8fcc-c5c9c331914b");
// The characteristic of the remote service we are interested in.
static BLEUUID charUUID("beb5483e-36e1-4688-b7f5-ea07361b26a8");
static BLEAddress *pServerAddress;
static boolean doConnect = false;
static boolean connected = false;
static BLERemoteCharacteristic* pRemoteCharacteristic;
static void notifyCallback(
BLERemoteCharacteristic* pBLERemoteCharacteristic,
uint8_t* pData,
size_t length,
bool isNotify) {
Serial.print("Notify callback for characteristic ");
Serial.print(pBLERemoteCharacteristic->getUUID().toString().c_str());
Serial.print(" of data length ");
Serial.println(length);
}
bool connectToServer(BLEAddress pAddress) {
Serial.print("Forming a connection to ");
Serial.println(pAddress.toString().c_str());
BLEClient* pClient = BLEDevice::createClient();
Serial.println(" - Created client");
// Connect to the remove BLE Server.
pClient->connect(pAddress);
Serial.println(" - Connected to server");
// Obtain a reference to the service we are after in the remote BLE server.
BLERemoteService* pRemoteService = pClient->getService(serviceUUID);
if (pRemoteService == nullptr) {
Serial.print("Failed to find our service UUID: ");
Serial.println(serviceUUID.toString().c_str());
return false;
}
Serial.println(" - Found our service");
// Obtain a reference to the characteristic in the service of the remote BLE server.
pRemoteCharacteristic = pRemoteService->getCharacteristic(charUUID);
if (pRemoteCharacteristic == nullptr) {
Serial.print("Failed to find our characteristic UUID: ");
Serial.println(charUUID.toString().c_str());
return false;
}
Serial.println(" - Found our characteristic");
// Read the value of the characteristic.
std::string value = pRemoteCharacteristic->readValue();
Serial.print("The characteristic value was: ");
Serial.println(value.c_str());
pRemoteCharacteristic->registerForNotify(notifyCallback);
}
/**
* Scan for BLE servers and find the first one that advertises the service we are looking for.
*/
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
/**
* Called for each advertising BLE server.
*/
void onResult(BLEAdvertisedDevice advertisedDevice) {
Serial.print("BLE Advertised Device found: ");
Serial.println(advertisedDevice.toString().c_str());
// We have found a device, let us now see if it contains the service we are looking for.
if (advertisedDevice.haveServiceUUID() && advertisedDevice.getServiceUUID().equals(serviceUUID)) {
//
Serial.print("Found our device! address: ");
advertisedDevice.getScan()->stop();
pServerAddress = new BLEAddress(advertisedDevice.getAddress());
doConnect = true;
} // Found our server
} // onResult
}; // MyAdvertisedDeviceCallbacks
void setup() {
Serial.begin(115200);
Serial.println("Starting Arduino BLE Client application...");
BLEDevice::init("");
// Retrieve a Scanner and set the callback we want to use to be informed when we
// have detected a new device. Specify that we want active scanning and start the
// scan to run for 30 seconds.
BLEScan* pBLEScan = BLEDevice::getScan();
pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
pBLEScan->setActiveScan(true);
pBLEScan->start(30);
} // End of setup.
// This is the Arduino main loop function.
void loop() {
// If the flag "doConnect" is true then we have scanned for and found the desired
// BLE Server with which we wish to connect. Now we connect to it. Once we are
// connected we set the connected flag to be true.
if (doConnect == true) {
if (connectToServer(*pServerAddress)) {
Serial.println("We are now connected to the BLE Server.");
connected = true;
} else {
Serial.println("We have failed to connect to the server; there is nothin more we will do.");
}
doConnect = false;
}
// If we are connected to a peer BLE Server, update the characteristic each time we are reached
// with the current time since boot.
if (connected) {
String newValue = "Time since boot: " + String(millis()/1000);
Serial.println("Setting new characteristic value to \"" + newValue + "\"");
// Set the characteristic's value to be the array of bytes that is actually a string.
pRemoteCharacteristic->writeValue(newValue.c_str(), newValue.length());
}
delay(1000); // Delay a second between loops.
} // End of loop
Client端代码稍微复杂些,但对应Server端也不难理解。在setup()中创建BLE设备并开启扫描模式,扫描附近所有的BLE Server。
找到一个Server就在Callback函数里对比Service和Characteristic的UUID码,对上后就停止扫描。在loop()函数里不断检查连接情况,并每次改写BLE Server的特征值。
BLE_Client示例演示了客户端如何扫描Server,并连接,对比UUID,读取并改写特征值的基本操作。
方式二:手机客户端
手机客户端配合BLE服务端是更常见的搭配,但关于手机APP如何调用系统蓝牙接口更多涉及的是手机移动端的编程:如果安卓系统你要懂Java和Android SDK,苹果系统则要懂Objective-C/Swift还有iOS的底层...总之又是另一个领域。如果你感兴趣,可以自行钻研,网上也不乏蓝牙APP开发的教程。这里我们使用Nordic半导体官方推出的BLE调试APP--nRF Connect来看看如何使用手机BLE Client如何查看我们之前创建的ESP32 BLE Server。
首先,我们在苹果商店或者安卓第三方商店搜索、下载并安装好nRF Connect。
打开APP后,我们就可以搜索附近的BLE设备,当然手机的蓝牙功能和相关权限要在设置里打开,否则APP会红字提示。
扫描一圈后,APP会列表显示所有扫描到的附近的BLE设备,找到我们自己命名的BLE Server点击Connect。
连接成功后,会跳转至设备页,里面详细罗列了这个Server所有的Services、Characteristic还有对应的UUID码。我们展开就可以看见自定义的特征值,也可以直接通过APP改写这个值。
结语
我们简单地介绍了蓝牙低功耗BLE和经典蓝牙BT的不同,BLE的数据结构,及如何用ESP32创建BLE的服务端和客户端。至此,蓝牙通信上下部分就完结了,在本系列的下一篇中,小编继续介绍Arduino无线通信里另外一个“半壁江山” -- WiFi通信。