源码:bluez_4.66.orig.tar.gz
编译
编译bluez-4.66时,在configure时,遇到如下dbus错误:
configure: error: D-Bus library is required
解决方法:
sudo apt-get install libdbus-1-dev libdbus-glib-1-dev
make -j4
最终产生bluetoothd,在src/.libs/目录下。
运行
在ubuntu下,系统启动时默认已经启动里了bluetoothd,只是这个bluetoothd位于/usr/sbin/下。我们可以用killall -9 bluetoothd将默认启动的bluetoothd干掉,然后手动
启动我们自己编译的bluetoothd,经检验,自己编译的bluetoothd也是可以配合运行的,基本配对传文件功能也正常。
我们用./bluetoothd -h查看bluetoothd运行命令,结果如下:
Usage:
bluetoothd [OPTION...]
Help Options:
-h, --help Show help options
Application Options:
-n, --nodaemon Don't run as daemon in background
-d, --debug=DEBUG Enable debug information output
-u, --udev Run from udev mode of operation
最简单的情况下,我们用sudo ./bluetoothd去启动bluetoothd程序。用sudo的原因就不需要讲了,因为程序本身用到里很多root权限。我们用这个命令启动后,发现程序马上
就进入后台运行了。在看上面help出来的结果,在后面加上-n参数,这时候发现程序在控制台运行,并且可以用ctrl+c终止程序。这里我主要是为了调试蓝牙模块,所以用
控制台跑程序,以便打印一些我要的信息。其他两个参数后面在研究。
代码解析
代码解析之:start_sdp_server(mtu, main_opts.deviceid, SDP_SERVER_COMPAT);
此部分代码在sdpd-server.c文件中,函数如下:
int start_sdp_server(uint16_t mtu, const char *did, uint32_t flags)
{
int compat = flags & SDP_SERVER_COMPAT;
int master = flags & SDP_SERVER_MASTER;
info("Starting SDP server");
if (init_server(mtu, master, compat) < 0) {
error("Server initialization failed");
return -1;
}
if (did && strlen(did) > 0) {
const char *ptr = did;
uint16_t vid = 0x0000, pid = 0x0000, ver = 0x0000;
vid = (uint16_t) strtol(ptr, NULL, 16);
ptr = strchr(ptr, ':');
if (ptr) {
pid = (uint16_t) strtol(ptr + 1, NULL, 16);
ptr = strchr(ptr + 1, ':');
if (ptr)
ver = (uint16_t) strtol(ptr + 1, NULL, 16);
register_device_id(vid, pid, ver);
}
}
//create a channel according to socket, just like create a port according to the socket
//then add io_accept_event func listen to the channel if there are someone connect to
//the channel, just like we create a port on linux, then we will listen to the port because
//there maybe someone connect to the port, here we act as a server.
l2cap_io = g_io_channel_unix_new(l2cap_sock);
g_io_channel_set_close_on_unref(l2cap_io, TRUE);
g_io_add_watch(l2cap_io, G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
io_accept_event, &l2cap_sock);
if (compat && unix_sock > fileno(stderr)) {
unix_io = g_io_channel_unix_new(unix_sock);
g_io_channel_set_close_on_unref(unix_io, TRUE);
g_io_add_watch(unix_io, G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
io_accept_event, &unix_sock);
}
return 0;
}
这个函数在最后创建里l2cap_io,并用io_accept_event接口侦听此channel。这里我的理解就类似于linux下我们创建端口port后,会用listen接口去侦听创建的端口,这样
一旦有client连接上来,我们就可以用accept接口去接受连接。这里我觉得应该原理相同,这里无非是用glib库实现而已。
接下来看io_accept_event这个接口:
static gboolean io_accept_event(GIOChannel *chan, GIOCondition cond, gpointer data)
{
GIOChannel *io;
int nsk;
if (cond & (G_IO_HUP | G_IO_ERR | G_IO_NVAL)) {
g_io_channel_unref(chan);
return FALSE;
}
if (data == &l2cap_sock) {
struct sockaddr_l2 addr;