BLE 使用 ESP 32

BLE using ESP 32

我正在尝试使用 ESP32 对 BLE 客户端进行编程。我使用了附加的代码(这是示例部分的示例代码)。我现在的问题是,如何让它只显示扫描设备的 MAC 地址,以及如何将此 MAC 地址更改为 LoRa 芯片的 JSON 格式发送?非常感谢您花时间阅读这篇文章 post。

/*
   Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleScan.cpp
   Ported to Arduino ESP32 by Evandro Copercini
*/

#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEScan.h>
#include <BLEAdvertisedDevice.h>

int scanTime = 5; //In seconds
BLEScan* pBLEScan;

class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
    void onResult(BLEAdvertisedDevice advertisedDevice) {
      Serial.printf("Advertised Device: %s \n", advertisedDevice.toString().c_str());
    }
};

void setup() {
  Serial.begin(115200);
  Serial.println("Scanning...");

  BLEDevice::init("");
  pBLEScan = BLEDevice::getScan(); //create new scan
  pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
  pBLEScan->setActiveScan(true); //active scan uses more power, but get results faster
  pBLEScan->setInterval(100);
  pBLEScan->setWindow(99);  // less or equal setInterval value
}

void loop() {
  // put your main code here, to run repeatedly:
  BLEScanResults foundDevices = pBLEScan->start(scanTime, false);
  Serial.print("Devices found: ");
  Serial.println(foundDevices.getCount());
  Serial.println("Scan done!");
  pBLEScan->clearResults();   // delete results fromBLEScan buffer to release memory
  delay(2000);
}

您的扫描结果是 foundDevices,其中包含所有找到的设备的列表。我们可以遍历它来访问设备。 List 包含 BLEAdvertisedDevices,它们有一个名为 getAddress() 的方法。地址可以使用 toString() 转换为字符串。您可以打印字符串或将其放入 json 容器中。

您的 loop-code 可能如下所示:

void loop() {
  // put your main code here, to run repeatedly:
  BLEScanResults foundDevices = pBLEScan->start(scanTime, false);
  Serial.print("Devices found: ");
  for (int i = 0; i < foundDevices.getCount(); ++i)
  {
    std::string address = foundDevices.getDevice(i).getAddress().toString();
    int rssi = foundDevices.getDevice(i).getRSSI();
    Serial.print(address.c_str());
    Serial.print(rssi);
    // TODO: Insert into JSON
  }
  Serial.println(foundDevices.getCount());
  Serial.println("Scan done!");
  pBLEScan->clearResults();   // delete results fromBLEScan buffer to release memory
  delay(2000);
}