Advertisement
TolentinoCotesta

ESP32 BLE Scan

Oct 23rd, 2020 (edited)
556
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 3.94 KB | None | 0 0
  1. #include <Arduino.h>
  2. #include <BLEDevice.h>
  3. #include <BLEUtils.h>
  4. #include <BLEScan.h>
  5. #include <BLEAdvertisedDevice.h>
  6.  
  7. // Pulsante per abilitare l'associazione del device
  8. const byte Button = 4;
  9.  
  10. // Per associare un dispositivo, questo deve essere molto vicino all'ESP32
  11. int linkRSSI = -69;
  12.  
  13. // Quando il dispositivo è abbastanza vicino, esegui azione
  14. int nearRSSI = -90;
  15.  
  16. // Variabile che diventa true quando il dispositivo è abbastanza vicino
  17. bool isNearDevice = false;
  18.  
  19. // Questa stringa andrà a memorizzare l'uuid dei device autorizzati
  20. // E' necessario usare std:string perché le funzioni restituiscono questo tipo di dati
  21. std::string allowedDevice;
  22.  
  23. // Durata minima dell'impulso di uscita
  24. #define MIN_PULSE_TIME 2000    
  25.  
  26.  
  27. BLEScan* pBLEScan;
  28.  
  29. class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
  30.     void onResult(BLEAdvertisedDevice advertisedDevice) {
  31.      
  32.       if (advertisedDevice.haveServiceUUID()){
  33.         std::string uuid = advertisedDevice.getServiceUUID().toString();
  34.         std::string mac_adr = advertisedDevice.getAddress().toString();
  35.         //Serial.printf("MAC %S - UUID %s\n", mac_adr.c_str(), uuid.c_str());
  36.        
  37.         // Cerca l'uuid nella std::string allowedDevice
  38.         std::size_t found = allowedDevice.find(uuid);  
  39.         bool authorized = (found != std::string::npos);
  40.  
  41.         // Aggiungo alla lista dei device ammessi se molto vicino e pulsante premuto
  42.         if(advertisedDevice.getRSSI() >= linkRSSI && digitalRead(Button) == LOW){
  43.          
  44.           // Se è già presente in lista -> authorized == true
  45.           if( !authorized) {
  46.             Serial.printf("Add to list allowed device: %s (%ddB)\n", uuid.c_str(), advertisedDevice.getRSSI());
  47.             allowedDevice += uuid;
  48.             allowedDevice += "\n";
  49.           }
  50.         }
  51.        
  52.         // Se il dispositivo è autorizzato ed è abbastanza vicino, isNearDevice -> true
  53.         if(advertisedDevice.getRSSI() > nearRSSI && authorized){
  54.           isNearDevice = true;
  55.           Serial.printf("Near authorized device found: %s\n", uuid.c_str());
  56.         }
  57.       }
  58.     }
  59. };
  60.  
  61. // Task che esegue continuamente lo scan dei device BLE raggiungibili
  62. void bleScanTask(void * taskPar){
  63.   Serial.print("Task is running on: ");
  64.   Serial.println(xPortGetCoreID());
  65.  
  66.   while(true) {
  67.     vTaskDelay(100 / portTICK_PERIOD_MS);
  68.     BLEScanResults foundDevices = pBLEScan->start(1, true); // duration( seconds), is_continue    
  69.     pBLEScan->clearResults();                               // delete results from BLEScan buffer
  70.   }
  71.  
  72.   Serial.println("Terminating BLE scanning task");
  73.   vTaskDelete(NULL);
  74. }
  75.  
  76.  
  77. void setup() {
  78.   pinMode(Button, INPUT_PULLUP);
  79.   pinMode(LED_BUILTIN, OUTPUT);
  80.   digitalWrite(LED_BUILTIN, LOW);
  81.  
  82.   Serial.begin(115200);
  83.   Serial.println("Scanning...");
  84.  
  85.   BLEDevice::init("");
  86.   pBLEScan = BLEDevice::getScan();  // Create new scan object
  87.   pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
  88.   pBLEScan->setActiveScan(true);    // Active scan uses more power, but get results faster
  89.   pBLEScan->setInterval(100);    
  90.   pBLEScan->setWindow(99);          // Less or equal setInterval value
  91.  
  92.   // Siccome l'esecuzione dello scanning è bloccante, facciamola in un task dedicato
  93.   xTaskCreate(
  94.     bleScanTask,     // Function to be called
  95.     "BLE Scan task", // Name of the task (for debugging)
  96.     2048,            // Stack size (bytes)
  97.     NULL,            // Parameter to pass
  98.     1,               // Task priority
  99.     NULL             // Task handle
  100.   );
  101. }
  102.  
  103. void loop() {
  104.  
  105.   // Un dispositivo è passato abbastanza vicino, attivo un segnale
  106.   static uint32_t pulseTime;    
  107.   if(isNearDevice) {
  108.     pulseTime = millis();
  109.     digitalWrite(BUILTIN_LED, HIGH);
  110.     isNearDevice = false;          
  111.   }
  112.  
  113.   // Il segnale è durato abbastanza -> reset
  114.   if(millis() - pulseTime > MIN_PULSE_TIME) {
  115.     digitalWrite(BUILTIN_LED, LOW);
  116.   }
  117.  
  118. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement