stopping scan after 30 seconds

zotech
Posts: 2
Joined: Wed Oct 10, 2018 4:00 pm

stopping scan after 30 seconds

Postby zotech » Wed Oct 10, 2018 4:26 pm

Hi,

Im trying to make an ESP32 scan for multiple beacons and turn on an LED once if the beacons are found.
I have been working with this code but I cant get it to stop scanning once the beacon is found.

What am I doing wrong here?
TIA!

Code: Select all


/*
 * 
 * This detects advertising messages of BLE devices and compares it with stored MAC addresses. 
 * If one matches, it sends an MQTT message to swithc something
   Copyright <2017> <Andreas Spiess>
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
  to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
  and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  DEALINGS IN THE SOFTWARE.
   
   Based on Neil Kolban's example file: https://github.com/nkolban/ESP32_BLE_Arduino
 */

#include "BLEDevice.h"

static BLEAddress *pServerAddress;

#define LED_GREEN 27
#define LED_RED 14
#define LED_BLUE 26
#define LED_WHITE 12
#define LED_CLEAR 13

BLEScan* pBLEScan;
BLEClient*  pClient;
bool deviceFound = false;
bool device2Found = false;

String knownAddresses[] = { "e0:e1:e2:e3:f1:97"};
String knownAddresses2[] = { "ff:ff:50:05:62:4a"};

 unsigned long entry;


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);
}

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());
      pServerAddress = new BLEAddress(advertisedDevice.getAddress());

      bool known = false;
      for (int i = 0; i < (sizeof(knownAddresses) / sizeof(knownAddresses[0])); i++) {
        if (strcmp(pServerAddress->toString().c_str(), knownAddresses[i].c_str()) == 0) known = true;
      }
      if (known) {
        Serial.print("Device found: ");
        Serial.println(advertisedDevice.getRSSI());
        if (advertisedDevice.getRSSI() > -100) deviceFound = true;
        else deviceFound = false;
        Serial.println(pServerAddress->toString().c_str());
        advertisedDevice.getScan()->stop();
      }
       for (int i = 0; i < (sizeof(knownAddresses2) / sizeof(knownAddresses2[0])); i++) {
        if (strcmp(pServerAddress->toString().c_str(), knownAddresses2[i].c_str()) == 0) known = true;
      }
      if (known) {
        Serial.print("Device found: ");
        Serial.println(advertisedDevice.getRSSI());
        if (advertisedDevice.getRSSI() > -100) device2Found = true;
        else device2Found = false;
        Serial.println(pServerAddress->toString().c_str());
        advertisedDevice.getScan()->stop();
      }
    }  
}; // MyAdvertisedDeviceCallbacks


void setup() {
  Serial.begin(115200);
  Serial.println("Starting Arduino BLE Client application...");
  pinMode(LED_BLUE, OUTPUT);
  pinMode(LED_RED, OUTPUT);
  pinMode(LED_GREEN, OUTPUT);
  pinMode(LED_WHITE, OUTPUT);
  pinMode(LED_CLEAR, OUTPUT);
  digitalWrite(LED_BLUE, HIGH);

  BLEDevice::init("");

  pClient  = BLEDevice::createClient();
  Serial.println(" - Created client");
  pBLEScan = BLEDevice::getScan();
  pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
  pBLEScan->setActiveScan(true);
  
}

void loop() {

  device1();
  device2();

}


void device1() {

  Serial.println();
  Serial.println("BLE Scan restarted.....");
  deviceFound = false;
  BLEScanResults scanResults = pBLEScan->start(30);
  if (deviceFound) {
    Serial.println("on");
    digitalWrite(LED_GREEN, HIGH);
    digitalWrite(LED_RED, LOW);  
    delay(5000);

  }
  else {
    Serial.println("off");
    digitalWrite(LED_GREEN, LOW);
    digitalWrite(LED_RED, HIGH);
   
  }
} 

void device2() {

  Serial.println();
  Serial.println("BLE Scan restarted.....");
  device2Found = false;
  BLEScanResults scanResults = pBLEScan->start(30);
  if (device2Found) {
    Serial.println("on");
    digitalWrite(LED_WHITE, HIGH);
    digitalWrite(LED_CLEAR, LOW);
    delay(5000);

  }
  else {
    Serial.println("off");
    digitalWrite(LED_WHITE, LOW);
    digitalWrite(LED_CLEAR, HIGH);
    
  }

  }


// End of loop

chegewara
Posts: 2364
Joined: Wed Jun 14, 2017 9:00 pm

Re: stopping scan after 30 seconds

Postby chegewara » Thu Oct 11, 2018 1:38 pm

Have you tried to move this into setup():

Code: Select all

  BLEScanResults scanResults = pBLEScan->start(0); // <-- 0 means scan forever
  


Also change this line, because your beacons will be reported only one time:

Code: Select all

  pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks(), true); // <-- true means you want duplicates, unless you dont
  
Or just add:

Code: Select all

advertisedDevice.getScan()->stop();
at beggining in onResult() function.

zotech
Posts: 2
Joined: Wed Oct 10, 2018 4:00 pm

Re: stopping scan after 30 seconds

Postby zotech » Thu Oct 11, 2018 3:59 pm

Thanks for the reply chegewara
I think by doing that I just messed up the code more.
Been working on it for the last 4 hours with no success still.

The problem is, I'm just learning how to code the ESP32 and working of a sketch provided by someone else.
I'm not even sure if I am doing this the most efficient way or if there is a much simpler way to achieve what I'm trying to do.

All I want to do is give the ESP32 a bunch of BLE mac address' and if they are found within a 10/20/30 second scan to turn on the corresponding green LED for that mac address and if not then turn on the red LED.
I only need the scan to run once as the button on the ESP32 will be used to do a scan when required.

chegewara
Posts: 2364
Joined: Wed Jun 14, 2017 9:00 pm

Re: stopping scan after 30 seconds

Postby chegewara » Fri Oct 12, 2018 1:00 pm

I am trying to improve this ble library and i found small bug in BLEScan.cpp, you can fix it easy. This will make your life easier.
add here vTaskDelay(1):
https://github.com/nkolban/ESP32_BLE_Ar ... n.cpp#L105

After that fix probably your code should work without changes.

chegewara
Posts: 2364
Joined: Wed Jun 14, 2017 9:00 pm

Re: stopping scan after 30 seconds

Postby chegewara » Sat Oct 13, 2018 12:17 pm

Yet again it was not the correct answer. Situation is more complicated than i initially thought. Problem is with esp-idf scanning function. It is problem because all bt tasks that are in esp-idf have high priority, so when you have scan for 30s then you wont be able anything in loop() for 30s. For you its not very big issue, because you can move those line at the end onResult callback:

Code: Select all

  device1();  // <--- remember to delete scan->start from this function
  device2();
and in loop you can only have call to scan->start().

I am thinking how to fix it in BLEScan, but i will have to consult my solution with espressif devs, because is somehow drastically.

BTW BLEScan has memory leak, here you can find fixed version:
https://gist.github.com/chegewara/6fc38 ... 4367aa33d1

Who is online

Users browsing this forum: No registered users and 68 guests