Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- 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 <Arduino.h>
- #include <sstream>
- #include <BLEAdvertisedDevice.h>
- #include <BLEDevice.h>
- #include <BLEScan.h>
- #include <BLEUtils.h>
- std::stringstream ss;
- BLEScan *pBLEScan;
- #ifndef LED_BUILTIN
- // Set LED_BUILTIN if it is not defined by Arduino framework
- #define LED_BUILTIN 2
- #endif
- int scanTime = 30; // In seconds
- class MyAdvertisedDeviceCallbacks : public BLEAdvertisedDeviceCallbacks {
- void onResult(BLEAdvertisedDevice advertisedDevice) {
- Serial.printf("Advertised Device: %s \n",
- advertisedDevice.toString().c_str());
- }
- };
- void setup() {
- Serial.begin(57600);
- Serial.setDebugOutput(true);
- Serial.println("Start Scanning...");
- pinMode(LED_BUILTIN, OUTPUT);
- digitalWrite(LED_BUILTIN, HIGH);
- BLEDevice::init("");
- // BLEScan *pBLEScan = BLEDevice::getScan(); // create new scan
- pBLEScan = BLEDevice::getScan(); // create new scan
- pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
- pBLEScan->setActiveScan(
- true); // active scan uses more power, but get results faster
- pBLEScan->setInterval(0x50);
- pBLEScan->setWindow(0x30);
- }
- void loop() {
- Serial.printf("\r\nNew scan start at %lu\r\n", millis());
- BLEScanResults foundDevices = pBLEScan->start(scanTime);
- Serial.print("Devices found: ");
- Serial.println(foundDevices.getCount());
- Serial.println("Scan done!");
- int count = foundDevices.getCount();
- ss.str("");
- ss.clear();
- ss << "[";
- for (int i = 0; i < count; i++) {
- if (i > 0) {
- ss << ",";
- }
- BLEAdvertisedDevice d = foundDevices.getDevice(i);
- ss << "{\"Address\":\"" << d.getAddress().toString()
- << "\",\"Rssi\":" << d.getRSSI();
- if (d.haveName()) {
- ss << ",\"Name\":\"" << d.getName() << "\"";
- }
- if (d.haveAppearance()) {
- ss << ",\"Appearance\":" << d.getAppearance();
- }
- if (d.haveManufacturerData()) {
- std::string md = d.getManufacturerData();
- uint8_t *mdp = (uint8_t *)d.getManufacturerData().data();
- char *pHex = BLEUtils::buildHexData(nullptr, mdp, md.length());
- ss << ",\"ManufacturerData\":\"" << pHex << "\"";
- free(pHex);
- }
- if (d.haveServiceUUID()) {
- ss << ",\"ServiceUUID\":\"" << d.getServiceUUID().toString() << "\"";
- }
- if (d.haveTXPower()) {
- ss << ",\"TxPower\":" << (int)d.getTXPower();
- }
- ss << "}";
- }
- ss << "]";
- Serial.println(String(ss.str().c_str()));
- digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
- delay(2000);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement