Eventually, I discovered the answers to all the questions I had.
I will start by answering the last question:
The commands I use only set-up the BLE device to advertise some data, but iOS reports that the connection is accepted. What part of bluez is accepting incoming connections?
This one was answered on the bluez mailing-list, in response to me.
Summary: the BLE connection is accepted at the HCI level by the kernel. If you want to use that connection from user space you need to use an l2cap socket with the ATT channel ID (which is 4).
Bleno has a good example of using an L2CAP socket.
How an L2CAP socket works is basically like this:
/* create L2CAP socket, and bind it to the local adapter */
l2cap_socket = socket(AF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_L2CAP);
hci_device_id = hci_get_route(NULL);
hci_socket = hci_open_dev(hci_device_id);
memset(&l2cap_address, sizeof(l2cap_address));
l2cap_address.l2_family = AF_BLUETOOTH;
l2cap_address.l2_bdaddr = hci_device_address;
l2cap_address.l2_cid = htobs(ATT_CID);
bind(l2cap_socket, (struct sockaddr*)&l2cap_address, sizeof(l2cap_address));
listen(l2cap_socket, 1);
while (1) {
/* now select and accept() client connections. */
select(l2cap_socket + 1, &afds, NULL, NULL, &tv);
client_socket = accept(l2cap_socket, (struct sockaddr *)&l2cap_address, &len);
/* you can now read() what the client sends you */
int ret = read(client_socket, buffer, sizeof(buffer));
printf("data len: %d
", ret);
for (i = 0; i < ret; i++) {
printf("%02x", ((int)buffer[i]) & 0xff);
}
printf("
");
close(client_socket);
}
How to advertise a service?
I realized I needed an answer to the previous question to answer that one.
Once you can read the data over L2CAP socket, everything makes more sense, for example, if your Android phone does gatt.discoverServices()
, then the little program above will read (i.e. receive):
10 0100 ffff 0028
Which basically means:
10: READ_BY_GROUP
0100: from handle 0001
ffff: to handle ffff
0028: with UUID 2800
This request is the way any BLE peripheral will request the list of services.
Then, you can answer this request with the list of services your device provides, formatted according to the GATT protocol.
Again, see the implementation of this in Bleno.