我尝试了不同的更改,但我不知道为什么当 BLE 外围设备断开连接时,中央没有得到确认或处理程序没有调用。
我修改了 gattlib 发现示例以断开处理程序。我的代码
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "gattlib.h"
void disconnectHandler(void *arg)
{
printf("in disconnection handler \n");
}
int main(int argc, char *argv[])
{
gatt_connection_t* connection;
gattlib_primary_service_t* services;
gattlib_characteristic_t* characteristics;
int services_count, characteristics_count;
char uuid_str[MAX_LEN_UUID_STR + 1];
int ret, i;
if (argc != 2) {
printf("%s <device_address>\n", argv[0]);
return 1;
}
connection = gattlib_connect(NULL, argv[1], GATTLIB_CONNECTION_OPTIONS_LEGACY_DEFAULT);
if (connection == NULL) {
fprintf(stderr, "Fail to connect to the bluetooth device.\n");
return 1;
}
if(gattlib_has_valid_handler(disconnectHandler) == 1)
{
printf("handler is valid\n");
gattlib_register_on_disconnect(connection, disconnectHandler, NULL);
}
else
{
printf("handler is not valid\n");
}
ret = gattlib_discover_primary(connection, &services, &services_count);
if (ret != GATTLIB_SUCCESS) {
fprintf(stderr, "Fail to discover primary services.\n");
return 1;
}
for (i = 0; i < services_count; i++) {
gattlib_uuid_to_string(&services[i].uuid, uuid_str, sizeof(uuid_str));
printf("service[%d] start_handle:%02x end_handle:%02x uuid:%s\n", i,
services[i].attr_handle_start, services[i].attr_handle_end,
uuid_str);
}
free(services);
ret = gattlib_discover_char(connection, &characteristics, &characteristics_count);
if (ret != GATTLIB_SUCCESS) {
fprintf(stderr, "Fail to discover characteristics.\n");
return 1;
}
for (i = 0; i < characteristics_count; i++) {
gattlib_uuid_to_string(&characteristics[i].uuid, uuid_str, sizeof(uuid_str));
printf("characteristic[%d] properties:%02x value_handle:%04x uuid:%s\n", i,
characteristics[i].properties, characteristics[i].value_handle,
uuid_str);
}
free(characteristics);
for(int i=0; i<100; i++)
{
sleep(1);
printf("In loop\n");
}
gattlib_disconnect(connection);
return 0;
}
在 100 秒睡眠部分,我正在断开外围设备但我没有收到 disconnectionHandler 调用。我是否在 gettlib 库中犯了任何基本错误或任何错误?我用 btmon 日志检查断开连接打印即将到来,但它对 gattlib 库或我的应用程序并不丰富。
btmod 日志:
Reason: Connection Timeout (0x08)
@ MGMT Event: Device Disconnected (0x000c) plen 8 {0x0002} [hci0] 327.987207
LE Address: 30:AE:A4:F5:FF:1E (Espressif Inc.)
Reason: Connection timeout (0x01)
@ MGMT Event: Device Disconnected (0x000c) plen 8 {0x0001} [hci0] 327.987207
LE Address: 30:AE:A4:F5:FF:1E (Espressif Inc.)
Reason: Connection timeout (0x01)
我正在使用 2020 年 7 月 21 日表示 gattlib 库的最新提交。