方法3-树莓派蓝牙rfcomm server创建手机通信
在树莓派下 输入指令
hciconfig
出现 hci0
可以使用rfcomm 的socket建立和手机蓝牙的通信,让树莓派做server,在上一篇文章中讲到,在不使用界面操作蓝牙的情况下,使用指令打开蓝牙,
可以被扫描,j监听接口,可以被连接到。大概流程是
hciconfig hci0 up ---> hciconfig hci0 piscan --->hciconfig watch hci0 ,当有外部的spp端口连接上会在 /dev 下生成rfcomm0的节点。这个时候可以调用
read 和write 函数来操作了。但是等待这个过程不容易判断。但是rfcomm 协议提供了socket ,在socket里边已经帮助解决了这个连接阻塞的实现。
手机做client。
源码如下
rfcommServer.c
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/rfcomm.h>
int main(int argc, char **argv)
{
struct sockaddr_rc loc_addr = { 0 }, rem_addr = { 0 };
char buf[1024] = { 0 };
int s, client, bytes_read;
socklen_t opt = sizeof(rem_addr);
// allocate socket
s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
// bind socket to port 1 of the first available
// local bluetooth adapter
loc_addr.rc_family = AF_BLUETOOTH;
loc_addr.rc_bdaddr = *BDADDR_ANY;
loc_addr.rc_channel = (uint8_t) 1;
bind(s, (struct sockaddr *)&loc_addr, sizeof(loc_addr));
// put socket into listening mode
listen(s, 1);
// accept one connection
client = accept(s, (struct sockaddr *)&rem_addr, &opt);
ba2str( &rem_addr.rc_bdaddr, buf );
fprintf(stderr, "accepted connection from %s\n", buf);
memset(buf, 0, sizeof(buf));
// read data from the client
while(1)
{
bytes_read = read(client, buf, sizeof(buf));
if( bytes_read > 0 ) {
printf("received [%s]\n", buf);
}
}
// close connection
close(client);
close(s);
return 0;
}
需要依赖的库为 Bluetooth
gcc - o main rfcommServer.c -lbluetooth
已验证通过。
参考
http://people.csail.mit.edu/albert/bluez-intro/x502.html


