我刚刚收到 ESP32C3 微控制器,只有一个智能灯泡可供学习。我先写了BLE扫描代码,找到了灯泡。打印连接所需的 UUID 和地址。它无法连接,但我开始认为服务 UUID 是错误的。我手机上的 BLE 扫描仪显示 7 个左右的服务。其中只有 2 个允许写入。这是我的代码。任何帮助将不胜感激。
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEScan.h>
#include <BLEAdvertisedDevice.h>
#include <BLEClient.h>
#include <BLEAddress.h>
#include <BLEHIDDevice.h>
// The BLE scan duration in seconds
#define BLE_SCAN_DURATION 5
// The MAC address of the Sylvania Smart+ bulb
#define SYLVANIA_SMART_BULB_ADDRESS "CHANGE ME"
// The service UUID and characteristic UUID of the Sylvania Smart+ bulb
#define SYLVANIA_SMART_BULB_SERVICE_UUID "CHANGE ME"
#define SYLVANIA_SMART_BULB_CHARACTERISTIC_UUID "CHANGE ME"
// Function to handle the BLE scan results
class MyAdvertisedDeviceCallbacks : public BLEAdvertisedDeviceCallbacks {
public:
void onResult(BLEAdvertisedDevice advertisedDevice) {
// Print the MAC address, service UUID, and characteristic UUID of the smart bulb
Serial.printf("Found smart bulb: %s\n", advertisedDevice.getAddress().toString().c_str());
Serial.printf("Service UUID: %s\n", advertisedDevice.getServiceUUID().toString().c_str());
Serial.printf("Characteristic UUID: %s\n", advertisedDevice.getServiceDataUUID().toString().c_str());
// Check if the smart bulb is the Sylvania Smart+ bulb
if (advertisedDevice.getAddress().toString() == SYLVANIA_SMART_BULB_ADDRESS) {
// Connect to the Sylvania Smart+ bulb
BLEClient* pClient = BLEDevice::createClient();
BLEAddress bulbAddress(SYLVANIA_SMART_BULB_ADDRESS);
pClient->connect(bulbAddress);
// Get the service and characteristic of the Sylvania Smart+ bulb
BLERemoteService* pService = pClient->getService(SYLVANIA_SMART_BULB_SERVICE_UUID);
BLERemoteCharacteristic* pCharacteristic = pService->getCharacteristic(SYLVANIA_SMART_BULB_CHARACTERISTIC_UUID);
// Turn off the Sylvania Smart+ bulb
pCharacteristic->writeValue("00 00 00 00 00 00");
// Disconnect from the Sylvania Smart+ bulb
pClient->disconnect();
}
}
};
void setup() {
Serial.begin(115200);
// Initialize the BLE device
BLEDevice::init("");
// Start the BLE scan
BLEScan* pScan = BLEDevice::getScan();
pScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
pScan->setActiveScan(true);
pScan->start(BLE_SCAN_DURATION);
}
void loop() {
// Do nothing in the loop
}
我尝试用我的 BLE 扫描仪应用程序编写 \Off \OFF \off 00 00 00 00 00 00 等,但仍然没有乐趣。
无论如何我仍然无法连接,所以这是一个两步问题。
您关闭灯泡的命令似乎格式错误。
pCharacteristic->writeValue("00 00 00 00 00 00"); <--- seems wrong
我查看了
writeValue()
方法的签名(如 BLERemoteCharacteristic 类中定义),看来您不应该发送一串十六进制值。
可用的签名有:
void BLERemoteCharacteristic::writeValue(std::string newValue, bool response)
void BLERemoteCharacteristic::writeValue(uint8_t newValue, bool response)
void BLERemoteCharacteristic::writeValue(uint8_t* data, size_t length, bool response)
并且 std::string 版本应该使用 实际数据 作为字符串。
假设你想发送6个零字节来关闭它,你可以这样做
uint8_t data[6] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
pCharacteristic->writeValue(data, 6, false);
虽然我找不到任何详细说明 Sylvania Smart+ 灯泡接受哪些命令的资源。