I’m developing a Bluetooth application for an embedded device on Ubuntu. I’m using the sd-bus library to pair a Bluetooth device with a given MAC address. The code I’ve written successfully initiates the pairing process and prompts a passkey confirmation dialog.
Here’s my current code:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <systemd/sd-bus.h>
#define _cleanup_(f) __attribute__((cleanup(f)))
#define DESTINATION "org.bluez"
#define INTERFACE "org.bluez.Device1"
static int log_error(int error, const char *message) {
errno = -error;
fprintf(stderr, "%s: %mn", message);
return error;
}
int bt_conn_control(char* bt_dev_mac) {
_cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
_cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
char *member_state = "Pair";
char *path = NULL;
int r;
path = malloc(sizeof("/org/bluez/hci0/dev_00_00_00_00_00_00"));
if (path == NULL) {
perror("Memory allocation failed");
return -1;
}
sprintf(path, "/org/bluez/hci0/dev_%c%c_%c%c_%c%c_%c%c_%c%c_%c%c",
bt_dev_mac[0], bt_dev_mac[1], bt_dev_mac[3], bt_dev_mac[4], bt_dev_mac[6], bt_dev_mac[7],
bt_dev_mac[9], bt_dev_mac[10], bt_dev_mac[12], bt_dev_mac[13], bt_dev_mac[15], bt_dev_mac[16]);
r = sd_bus_open_system(&bus);
if (r < 0) {
free(path);
return log_error(r, "Failed to acquire bus");
}
r = sd_bus_call_method(bus, DESTINATION, path, INTERFACE, member_state, &error, NULL, NULL, NULL);
if (r < 0) {
free(path);
return log_error(r, "Method call failed");
}
free(path);
return 0;
}
int main() {
bt_conn_control("3C:19:5E:F9:26:60");
return 0;
}
When this code executes, a popup appears with the passkey and the device name. I want to handle the passkey confirmation programmatically within my application, instead of relying on the Ubuntu UI.
Additionally, how can I check for external pairing requests and manage them within the same application?