I am a beginner in writing code for BLE development. I am trying to write a straightforward code to scan for BLE devices on RPI using gattlib library in C++.
The program code is as follows:
#include <mutex>
#include <iostream>
#include <gattlib.h>
#define BLE_SCAN_TIMEOUT 5
// We use a mutex to make the BLE connections synchronous
std::mutex g_mutex;
static void ble_discovered_device(void *adapter, const char* addr, const char* name, void *user_data) {
std::cout << "check 2a\n";
if (name) {
printf("Discovered %s - '%s'\n", addr, name);
} else {
printf("Discovered %s\n", addr);
}
}
int main() {
int ret;
void *adapter;
// open adapter for communication
ret = gattlib_adapter_open(NULL, &adapter);
if (ret) {
std::cout << "[Error] Failed to open adapter.\n";
goto EXIT;
}
std::cout << "[INFO] starting scan for BLE devices\n";
std::cout << "check 1\n";
// lock thread
g_mutex.lock();
std::cout << "check 2\n";
// enable scan
ret = gattlib_adapter_scan_enable(adapter, ble_discovered_device, BLE_SCAN_TIMEOUT, NULL /* user_data */);
std::cout << "check 3\n";
if (ret) {
std::cout << "[Error] Failed to scan.\n";
goto EXIT;
}
// disable scan
ret = gattlib_adapter_scan_disable(adapter);
// unlock thread
g_mutex.unlock();
std::cout << "[INFO] stopping scan\n";
// close adapter
ret = gattlib_adapter_close(adapter);
EXIT:
std::cout << "[INFO] exit \n";
}
However the debug statement "check 2a" and "check 3" is not printed. The Bluetooth adapter opens successfully. The terminal logs are as follows:
[INFO] starting scan for BLE devices
check 1
check 2
Fatal Python error: take_gil: PyMUTEX_LOCK(gil->mutex) failed
Python runtime state: unknown
I am using the following command to run my code:
g++ blescan.cpp -o blescan -lgattlib
I have verified that the bluetooth adapter is working on the Raspberry Pi via bluetoothctl.
I am quite unsure what is going wrong here. I am not using python in this code. Thanks for the help!