Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot connect to ESP 32 BLE device. #369

Closed
Danjuanlab opened this issue Nov 28, 2020 · 13 comments
Closed

Cannot connect to ESP 32 BLE device. #369

Danjuanlab opened this issue Nov 28, 2020 · 13 comments
Assignees
Labels
Backend: pythonnet Issues or PRs relating to the .NET/pythonnet backend

Comments

@Danjuanlab
Copy link

Danjuanlab commented Nov 28, 2020

  • bleak version:0.9.1
  • Python version:3.6.8
  • Operating System:WIN10 1809
  • BlueZ version (bluetoothctl -v) in case of Linux:

Description

I want to connect to the BLE device of ESP 32 board through bleak, but I cannot connect to the device. The BLE_notify case code is running on ESP32. When using bleak to connect to the case code, it will prompt

File "C:\Programs\Python\Python36\lib\asyncio\tasks.py", line 362, in wait_for
     raise futures.TimeoutError()
concurrent.futures._base.TimeoutError

or 

bleak.exc.BleakError: Device with address 24:6F:28:CB:72:9E was not found.

When using the discover.py to scan board, it takes at least 7 times to run the code to recognize the ESP32 development board. I don't know which part of the problem is wrong.

ESP 32 CODE:

#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>

BLEServer* pServer = NULL;
BLECharacteristic* pCharacteristic = NULL;
bool deviceConnected = false;
bool oldDeviceConnected = false;
uint32_t value = 123;

// See the following for generating UUIDs:
// https://www.uuidgenerator.net/

#define SERVICE_UUID        "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"


class MyServerCallbacks: public BLEServerCallbacks {
    void onConnect(BLEServer* pServer) {
      deviceConnected = true;
    };

    void onDisconnect(BLEServer* pServer) {
      deviceConnected = false;
    }
};



void setup() {
  Serial.begin(115200);

  // Create the BLE Device
  BLEDevice::init("ESP32test");

  // Create the BLE Server
  pServer = BLEDevice::createServer();
  pServer->setCallbacks(new MyServerCallbacks());

  // Create the BLE Service
  BLEService *pService = pServer->createService(SERVICE_UUID);

  // Create a BLE Characteristic
  pCharacteristic = pService->createCharacteristic(
                      CHARACTERISTIC_UUID,
                      BLECharacteristic::PROPERTY_READ   |
                      BLECharacteristic::PROPERTY_WRITE  |
                      BLECharacteristic::PROPERTY_NOTIFY |
                      BLECharacteristic::PROPERTY_INDICATE
                    );

  // https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.gatt.client_characteristic_configuration.xml
  // Create a BLE Descriptor
  pCharacteristic->addDescriptor(new BLE2902());

  // Start the service
  pService->start();

  // Start advertising
  BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
  pAdvertising->addServiceUUID(SERVICE_UUID);
  pAdvertising->setScanResponse(false);
  pAdvertising->setMinPreferred(0x0);  // set value to 0x00 to not advertise this parameter
  BLEDevice::startAdvertising();
  Serial.println("Waiting a client connection to notify...");
}

void loop() {
    Serial.println("deviceConnected");
    Serial.println(deviceConnected);
    // notify changed value
    if (deviceConnected) {
        //pCharacteristic->setValue((uint8_t*)&value, 4);
        pCharacteristic->setValue("ceshi");
        pCharacteristic->notify();
        value++;
        Serial.println("connected");
        delay(3000); // bluetooth stack will go into congestion, if too many packets are sent, in 6 hours test i was able to go as low as 3ms
    }
    // disconnecting
    if (!deviceConnected && oldDeviceConnected) {
        delay(500); // give the bluetooth stack the chance to get things ready
        pServer->startAdvertising(); // restart advertising
        Serial.println("start advertising");
        oldDeviceConnected = deviceConnected;
    }
    // connecting
    if (deviceConnected && !oldDeviceConnected) {
        // do stuff here on connecting
        oldDeviceConnected = deviceConnected;
    }
}

code

@hbldh
Copy link
Owner

hbldh commented Dec 3, 2020

Try using a longer timeout for both discover and connect. See e.g. BleakClient docs or the BleakScanner docs.

@hbldh hbldh self-assigned this Dec 3, 2020
@hbldh hbldh added the Backend: pythonnet Issues or PRs relating to the .NET/pythonnet backend label Dec 3, 2020
@Danjuanlab
Copy link
Author

Try using a longer timeout for both discover and connect. See e.g. BleakClient docs or the BleakScanner docs.

I tried to set the timeout to 20, and discover() function 90% scan to ESP 32 devices, but the connection and printing service still reports an error, even if the timeout is set to 50S, the device still cannot be found.
scanner
connect2
connect

@hbldh
Copy link
Owner

hbldh commented Dec 4, 2020

I have no idea why, I'm sorry. I cannot reproduce it since none of my devices produce the same behaviour. Can you connect to it from other BLE client software?

@Danjuanlab
Copy link
Author

I have no idea why, I'm sorry. I cannot reproduce it since none of my devices produce the same behaviour. Can you connect to it from other BLE client software?

I can use the ble scanner app on my iphone 12 to connect to the ESP32 development board without fail.

@dlech
Copy link
Collaborator

dlech commented Dec 7, 2020

I would suggest logging Bluetooth packets. Windows may be doing something different from the iPhone that the ESP32 doesn't respond to. See https://bleak.readthedocs.io/en/latest/troubleshooting.html.

@Danjuanlab
Copy link
Author

I would suggest logging Bluetooth packets. Windows may be doing something different from the iPhone that the ESP32 doesn't respond to. See https://bleak.readthedocs.io/en/latest/troubleshooting.html.

捕获3
In the afternoon, I used two ESP32 boards of different models for testing. One of them was successfully connected and printed out the Services during the first connection. This was my first connection. This board has also been tested before. This is my first successful connection in history.In subsequent tests, all connections failed.

@dlech
Copy link
Collaborator

dlech commented Dec 7, 2020

I actually meant logging the packets from the Bluetooth radio, rather than enabling bleak logging. https://bleak.readthedocs.io/en/latest/troubleshooting.html#capture-bluetooth-traffic

@Danjuanlab
Copy link
Author

bth_hci.zip

I actually meant logging the packets from the Bluetooth radio, rather than enabling bleak logging. https://bleak.readthedocs.io/en/latest/troubleshooting.html#capture-bluetooth-traffic

@dlech
Copy link
Collaborator

dlech commented Jan 11, 2021

here is the decoded data that can be opened with wireshark: issue369.zip

There are a bunch of notifications that are received before the scanning starts. Is is possible that the ESP32 starts sending notifications before a connection is made?

@Danjuanlab
Copy link
Author

Danjuanlab commented Jan 12, 2021

here is the decoded data that can be opened with wireshark: issue369.zip

There are a bunch of notifications that are received before the scanning starts. Is is possible that the ESP32 starts sending notifications before a connection is made?

I use the sample code in arduino. From the code point of view, esp32 needs to establish a connection before it broadcasts the notify information. It is advertising at the beginning, which is in line with the steps and methods for BLE to establish a connection. There is no problem with the connection establishment on the mobile phone. I think this should be a problem with the connection code in win10.

/*    Video: https://www.youtube.com/watch?v=oCMOYS71NIU
    Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleNotify.cpp
    Ported to Arduino ESP32 by Evandro Copercini
    updated by chegewara

   Create a BLE server that, once we receive a connection, will send periodic notifications.
   The service advertises itself as: 4fafc201-1fb5-459e-8fcc-c5c9c331914b
   And has a characteristic of: beb5483e-36e1-4688-b7f5-ea07361b26a8

   The design of creating the BLE server is:
   1. Create a BLE Server
   2. Create a BLE Service
   3. Create a BLE Characteristic on the Service
   4. Create a BLE Descriptor on the characteristic
   5. Start the service.
   6. Start advertising.

   A connect hander associated with the server starts a background task that performs notification
   every couple of seconds.
*/
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>

BLEServer* pServer = NULL;
BLECharacteristic* pCharacteristic = NULL;
bool deviceConnected = false;
bool oldDeviceConnected = false;
uint32_t value = 0;

// See the following for generating UUIDs:
// https://www.uuidgenerator.net/

#define SERVICE_UUID        "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"


class MyServerCallbacks: public BLEServerCallbacks {
    void onConnect(BLEServer* pServer) {
      deviceConnected = true;
    };

    void onDisconnect(BLEServer* pServer) {
      deviceConnected = false;
    }
};



void setup() {
  Serial.begin(115200);

  // Create the BLE Device
  BLEDevice::init("ESP32");

  // Create the BLE Server
  pServer = BLEDevice::createServer();
  pServer->setCallbacks(new MyServerCallbacks());

  // Create the BLE Service
  BLEService *pService = pServer->createService(SERVICE_UUID);

  // Create a BLE Characteristic
  pCharacteristic = pService->createCharacteristic(
                      CHARACTERISTIC_UUID,
                      BLECharacteristic::PROPERTY_READ   |
                      BLECharacteristic::PROPERTY_WRITE  |
                      BLECharacteristic::PROPERTY_NOTIFY |
                      BLECharacteristic::PROPERTY_INDICATE
                    );

  // https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.gatt.client_characteristic_configuration.xml
  // Create a BLE Descriptor
  pCharacteristic->addDescriptor(new BLE2902());

  // Start the service
  pService->start();

  // Start advertising
  BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
  pAdvertising->addServiceUUID(SERVICE_UUID);
  pAdvertising->setScanResponse(false);
  pAdvertising->setMinPreferred(0x0);  // set value to 0x00 to not advertise this parameter
  BLEDevice::startAdvertising();
  Serial.println("Waiting a client connection to notify...");
}

void loop() {
    // notify changed value
    if (deviceConnected) {
        pCharacteristic->setValue((uint8_t*)&value, 4);
        pCharacteristic->notify();
        value++;
        delay(3); // bluetooth stack will go into congestion, if too many packets are sent, in 6 hours test i was able to go as low as 3ms
    }
    // disconnecting
    if (!deviceConnected && oldDeviceConnected) {
        delay(500); // give the bluetooth stack the chance to get things ready
        pServer->startAdvertising(); // restart advertising
        Serial.println("start advertising");
        oldDeviceConnected = deviceConnected;
    }
    // connecting
    if (deviceConnected && !oldDeviceConnected) {
        // do stuff here on connecting
        oldDeviceConnected = deviceConnected;
    }
}

@chandong83
Copy link

chandong83 commented Apr 24, 2021

@Danjuanlab @dlech When both indicate and notify are in the property, it was confirmed that only indicate is called in the start_notify callback.
so I will check the start_notify code.

@dlech
Copy link
Collaborator

dlech commented Oct 7, 2021

it was confirmed that only indicate is called in the start_notify callback.

We just changed the default in #620

@dlech
Copy link
Collaborator

dlech commented Jul 25, 2022

closing as duplicate of #604

@dlech dlech closed this as completed Jul 25, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Backend: pythonnet Issues or PRs relating to the .NET/pythonnet backend
Projects
None yet
Development

No branches or pull requests

4 participants