一、BlueZ在ubuntu PC上的基础应用

1、bluez的安装及基本功能

dong@ubuntu:~/bluez$ ls
bluez-5.47.tar.xz   SPP-loopback.py
dong@ubuntu:~/bluez$ tar xvf bluez-5.47.tar.xz
dong@ubuntu:~/bluez/bluez-5.47$ ./configure --prefix=/usr --mandir=/usr/share/man --sysconfdir=/etc --localstatedir=/var
make
make install

装完bluez,然后插上蓝牙适配器就可以测试了,如果不能启动就注销或者重启一下电脑。

2、bluez配对
dong@ubuntu:~/bluez/bluez-5.47$ cd test/
dong@ubuntu:~/bluez/bluez-5.47/test$ python simple-agent
Agent registered

然后可以用手机蓝牙助手(Bluetooth spp pro/蓝牙串口助手 Pro)来扫描配对蓝牙适配器,ubuntu上的simple-agent会弹出配对确认信息,输入yes回车完成配对

simple-agent是通过主从机之间的交互来实现的,可以实现加密配对。

3、bluez spp蓝牙透传demo

SPP-loopback.py和bluez5-spp-example分别是用python和c语言实现的SPP Demo

如果是ubuntu版本太低,安装bluez可能会缺一些库文件,装上库文件即可,可以参考http://blog.csdn.net/twy76/article/details/23851587

PC上也可以用图形工具来配置蓝牙,blueman-applet比较方便。

4、BlueZ文件共享

示例:BlueZ设备(这里是ubuntu PC)与手机之间的文件收发

  1. dong@dong-ubuntu:~$ lsusb
  2. Bus Device : ID 1d6b: Linux Foundation 3.0 root hub
  3. Bus Device : ID 0a12: Cambridge Silicon Radio, Ltd Bluetooth Dongle (HCI mode)
  4. Bus Device : ID 17ef: Lenovo
  5. Bus Device : ID 1d6b: Linux Foundation 2.0 root hub
  6. dong@dong-ubuntu:~$ hciconfig -a
  7. hci0: Type: BR/EDR Bus: USB
  8. BD Address: :1A:7D:DA:: ACL MTU: : SCO MTU: :
  9. UP RUNNING PSCAN ISCAN
  10. RX bytes: acl: sco: events: errors:
  11. TX bytes: acl: sco: commands: errors:
  12. Features: 0xff 0xff 0x8f 0xfe 0xdb 0xff 0x5b 0x87
  13. Packet type: DM1 DM3 DM5 DH1 DH3 DH5 HV1 HV2 HV3
  14. Link policy: RSWITCH HOLD SNIFF PARK
  15. Link mode: SLAVE ACCEPT
  16. Name: 'BlueZ 5.47'
  17. Class: 0x0c0104
  18. Service Classes: Rendering, Capturing
  19. Device Class: Computer, Desktop workstation
  20. HCI Version: 4.0 (0x6) Revision: 0x22bb
  21. LMP Version: 4.0 (0x6) Subversion: 0x22bb
  22. Manufacturer: Cambridge Silicon Radio ()
  23.  
  24. dong@dong-ubuntu:~$ hcitool scan
  25. Scanning ...
  26. ::::: ZHDZXD
  27. ::A2:CC::D8 ZHDGIS
  28. ::0A::C5: wifitest
  29. E4::DA:6E:8D: 小米手机
  30. :C3:::2E: Honor Lite
  31. dong@dong-ubuntu:~$ sdptool browse E4::DA:6E:8D:
  32. Browsing E4::DA:6E:8D: ...
  33. Service RecHandle: 0x10000
  34. Service Class ID List:
  35. "Generic Attribute" (0x1801)
  36. Protocol Descriptor List:
  37. "L2CAP" (0x0100)
  38. PSM:
  39. "ATT" (0x0007)
  40. uint16: 0x0001
  41. uint16: 0x0005
  42. ...
  43. ...

  44. Browsing E4::DA:6E:8D: ...
  45. Service Search failed: Invalid argument
  46. Service Name: OBEX Object Push
  47. Service RecHandle: 0x1000b
  48. Service Class ID List:
  49. "OBEX Object Push" (0x1105)
  50. Protocol Descriptor List:
  51. "L2CAP" (0x0100)
  52. "RFCOMM" (0x0003)
  53. Channel:
  54. "OBEX" (0x0008)
  55. Profile Descriptor List:
  56. "OBEX Object Push" (0x1105)
  57. Version: 0x0102
  58. Browsing E4::DA:6E:8D: ...
  59. Service Search failed: Invalid argument
  60.  
  61. //send file to moble
  62. dong@dong-ubuntu:~$ obex_test -b E4::DA:6E:8D:
  63. Using Bluetooth RFCOMM transport
  64. OBEX Interactive test client/server.
  65. > c
  66. Made some progress...
  67. Connect OK!
  68. Version: 0x10. Flags: 0x00
  69. > x
  70. PUSH file> test.txt
  71. name=test.txt, size=
  72. Going to send test.txt(test.txt), bytes
  73. Filling stream!
  74. Filling stream!
  75. Made some progress...
  76. Made some progress...
  77. PUT successful!
  78. > q
  79.  
  80. dong@dong-ubuntu:~$ sudo sdptool add OPUSH
  81. OBEX Object Push service registered
  82. dong@dong-ubuntu:~$ sudo sdptool browse local
  83. Browsing FF:FF:FF::: ...
  84. Service RecHandle: 0x10000
  85. Service Class ID List:
  86. "PnP Information" (0x1200)
  87. Profile Descriptor List:
  88. "PnP Information" (0x1200)
  89. Version: 0x0103
  90. ...
  91. ...
  92.  
  93. Service Name: OBEX Object Push
  94. Service RecHandle: 0x10008
  95. Service Class ID List:
  96. "OBEX Object Push" (0x1105)
  97. Protocol Descriptor List:
  98. "L2CAP" (0x0100)
  99. "RFCOMM" (0x0003)
  100. Channel:
  101. "OBEX" (0x0008)
  102. Profile Descriptor List:
  103. "OBEX Object Push" (0x1105)
  104. Version: 0x0100
  105.  
  106. //receive file from moble
  107. dong@dong-ubuntu:~$ obex_test -b local
  108. Using Bluetooth RFCOMM transport
  109. OBEX Interactive test client/server.
  110. > s
  111. OBEX_HandleInput() returned
  112. Unknown event 0b!
  113. connect_server()
  114. connect_server() Skipped header c0
  115. Made some progress...
  116. Server request finished!
  117. server_done() Command () has now finished
  118. OBEX_HandleInput() returned
  119. Made some progress...
  120. OBEX_HandleInput() returned
  121. Made some progress...
  122. OBEX_HandleInput() returned
  123. Made some progress...
  124. OBEX_HandleInput() returned
  125. ...
  126. ...
  127. Made some progress...
  128. OBEX_HandleInput() returned
  129. put_server()
  130. put_server() Found name
  131. put_server() Skipped header
  132. put_server() Skipped header c3
  133. put_server() Found body
  134. Filename = Screenshot_2017------059_com.baidu.searchbox.png
  135. Wrote Screenshot_2017------059_com.baidu.searchbox.png ( bytes)
  136. Made some progress...
  137. Server request finished!
  138. server_done() Command () has now finished
  139. OBEX_HandleInput() returned
  140. Unknown event 0b!
  141. We got a disconnect-request
  142. Made some progress...
  143. Server request finished!
  144. Disconnect done!
  145. OBEX_HandleInput() returned
  146. >

二、BlueZ在ARM上的基础应用

1、BlueZ移植

BlueZ依赖的第三方库比较多,编译起来很繁琐,给每个库都创建一个config.sh文件,并设置777权限,

创建安装目录/usr/local/bluez,也设置777权限,

如下依次运行每个库的配置文件./config.sh可完整的编译出ARM的可执行文件。

编译环境

ubuntu + linaro gcc

gcc编译器https://www.linaro.org/downloads/

硬件环境

CPU: Cortex A5

Bluetooth: wg7813(bluetooth和wifi的复合模块,芯片是TI的wl18xx)

移植主要参考这个wiki,依赖库的版本最好也按wiki里的版本,一堆开源库,不同版本会有冲突,wiki里的版本是一次编译通过,配合如下脚本。

http://wiki.beyondlogic.org/index.php?title=Cross_Compiling_BlueZ_Bluetooth_tools_for_ARM

1) zlib-1.2.

  1. #!/bin/bash
  2. cd /home/dong/bluez/zlib-1.2.
  3. CC=arm-linux-gnueabihf-gcc \
  4. AR=arm-linux-gnueabihf-ar \
  5. RANLIB=arm-linux-gnueabihf-ranlib \
  6. ./configure --prefix=/usr/local/bluez
  7.  
  8. make
  9. if [ $? == ]; then
  10. make install
  11. else
  12. echo -e "\n\tmake fail\n"
  13. fi

zlib第一次还不能运行脚本,一步一步来,其他库都能通过脚本自动化编译,安装。

Download, cross compile and install the zlib compression libraries. Configure doesn't accept the --host parameter (reports unknown option), so you need to hack the makefile.

  1. wget http://zlib.net/zlib-1.2.8.tar.gz
  2. tar -xzf zlib-1.2.8.tar.gz
  3. cd zlib-1.2.8/
  4. ./configure --prefix=/usr/local/bluez

Edit the makefile and prefix the build tools with arm-linux-gnueabi-.

  1. CC=arm-linux-gnueabihf-gcc
  2. LDSHARED=arm-linux-gnueabihf-gcc -shared -Wl,-soname,libz.so.1,--version-script,zlib.map
  3. CPP=arm-linux-gnueabihf-gcc -E
  4. AR=arm-linux-gnueabihf-ar
  5. RANLIB=arm-linux-gnueabihf-ranlib

Make and install:

  1. make
  2. make install

2) libffi-3.0.13

  1. #!/bin/bash
  2. ./configure --host=arm-linux-gnueabihf --prefix=/usr/local/bluez
  3.  
  4. make
  5. if [ $? == ]; then
  6. make install
  7. else
  8. echo -e "\n\tmake fail\n"
  9. fi

3) glib-2.40.0

  1. #!/bin/bash
  2. ./configure --host=arm-linux-gnueabihf \
  3. LIBFFI_CFLAGS="-I/usr/local/bluez/lib/libffi-3.0.13/include" \
  4. LIBFFI_LIBS="-lffi -L/usr/local/bluez/lib" \
  5. ZLIB_CFLAGS="-I/usr/local/bluez/include" \
  6. ZLIB_LIBS="-lz -L/usr/local/bluez/lib" \
  7. --prefix=/usr/local/bluez PKG_CONFIG_PATH=/usr/local/bluez/lib/pkgconfig glib_cv_stack_grows=no glib_cv_uscore=yes ac_cv_func_posix_getpwuid_r=yes ac_cv_func_posix_getgrgid_r=yes
  8.  
  9. make
  10. if [ $? == ]; then
  11. make install
  12. else
  13. echo -e "\n\tmake fail\n"
  14. fi

报错configure: error: Could not find a glib-genmarshal in your PATH,缺了libglib2.0-dev

sudo apt-get install libglib2.0-dev

4) expat-2.1.0

  1. #!/bin/bash
  2. ./configure --host=arm-linux-gnueabihf --prefix=/usr/local/bluez
  3.  
  4. make
  5. if [ $? == ]; then
  6. make install
  7. else
  8. echo -e "\n\tmake fail\n"
  9. fi

5) dbus-1.8.0

  1. #!/bin/bash
  2. ./configure --host=arm-linux-gnueabihf --prefix=/usr/local/bluez PKG_CONFIG_PATH=/usr/local/bluez/lib/pkgconfig \
  3. --disable-tests \
  4. --sysconfdir=/usr/local/bluez/etc \
  5. --localstatedir=/usr/local/bluez/var \
  6. --enable-user-session \
  7. --disable-doxygen-docs \
  8. --disable-xml-docs \
  9. --disable-static \
  10. --docdir=/usr/local/bluez/share/doc/dbus-1.8. \
  11. --with-console-auth-dir=/usr/local/bluez/var/run/console \
  12. --with-system-pid-file=/usr/local/bluez/var/run/dbus/pid \
  13. --with-system-socket=/usr/local/bluez/var/run/dbus/system_bus_socket \
  14. CPPFLAGS='-I/usr/local/bluez/include/' \
  15. CFLAGS='-I/usr/local/bluez/include/' \
  16. LDFLAGS='-L/usr/local/bluez/lib'
  17.  
  18. make
  19. if [ $? == ]; then
  20. make install
  21. else
  22. echo -e "\n\tmake fail\n"
  23. fi

6) libical-1.0

  1. #!/bin/bash
  2. export CC=arm-linux-gnueabihf-gcc
  3. export CXX=arm-linux-gnueabihf-g++
  4. cmake -DCMAKE_INSTALL_PREFIX=/usr/local/bluez
  5.  
  6. make
  7. if [ $? == ]; then
  8. make install
  9. else
  10. echo -e "\n\tmake fail\n"
  11. fi

7) ncurses-5.9

  1. #!/bin/bash
  2. cd /home/dong/bluez/ncurses-5.9
  3. ./configure --prefix=/usr/local/bluez --with-shared \
  4. CC=arm-linux-gnueabihf-gcc \
  5. CXX=arm-linux-gnueabihf-g++ \
  6. --host=arm-linux-gnueabihf
  7.  
  8. make
  9. if [ $? == ]; then
  10. make install
  11. else
  12. echo -e "\n\tmake fail\n"
  13. fi

8) readline-6.3

  1. #!/bin/bash
  2. ./configure --host=arm-linux-gnueabihf --prefix=/usr/local/bluez bash_cv_wcwidth_broken=yes \
  3. PKG_CONFIG_PATH=/usr/local/bluez/lib/pkgconfig \
  4. CPPFLAGS='-I/usr/local/bluez/include/' \
  5. CFLAGS='-I/usr/local/bluez/include/' \
  6. LDFLAGS='-lncurses -L/usr/local/bluez/lib'
  7.  
  8. #make SHLIB_LIBS=-lncurses
  9. make
  10. if [ $? == ]; then
  11. make install
  12. else
  13. echo -e "\n\tmake fail\n"
  14. fi

9) bluez-5.18

  1. #!/bin/bash
  2. ./configure --host=arm-linux-gnueabihf \
  3. --prefix=/usr/local/bluez \
  4. CC="arm-linux-gnueabihf-gcc \
  5. -L/usr/local/bluez/lib \
  6. -I/usr/local/bluez/include \
  7. -I/usr/local/bluez/include/glib-2.0 \
  8. -I/usr/local/bluez/include/dbus-1.0 \
  9. -I/usr/local/bluez/lib/glib-2.0/include \
  10. -I/usr/local/bluez/lib/dbus-1.0/include \
  11. -I/usr/local/bluez/lib/libffi-3.0./include " \
  12. PKG_CONFIG_PATH=/usr/local/bluez/lib/pkgconfig \
  13. CPPFLAGS='-I/usr/local/bluez/include/' \
  14. CFLAGS='-I/usr/local/bluez/include/' \
  15. LDFLAGS='-lrt -lreadline -lncurses -L/usr/local/bluez/lib' \
  16. --disable-systemd --disable-udev --disable-cups --enable-library
  17.  
  18. make
  19. if [ $? == ]; then
  20. make install
  21. else
  22. echo -e "\n\tmake fail\n"
  23. fi

再次说明版本务必要匹配,否则会冲突,怎么检查版本匹配,暂时不清楚,新版本库匹配在下面这网站去找,下面两个版本都有匹配好的BlueZ Dependencies

BlueZ-5.46

http://www.linuxfromscratch.org/blfs/view/stable/general/bluez.html

BlueZ-5.48

http://www.linuxfromscratch.org/blfs/view/svn/general/bluez.html

2、板载bluez调试

1)linux内核配置bluetooth驱动参考 http://blog.csdn.net/new_abc/article/details/7639326 (bluetooth和wifi)
 [*]Networking support  --->

<*>   Bluetooth subsystem support  ---> //蓝牙子系统必须选择

<*>   L2CAP protocol suppor                  //逻辑链路控制和适配协议。

<*>   SCO links support                          //蓝牙语音和耳机支持

<*>   RFCOMM protocol suppor             //面向流的传输协议,支持拨号网络等

[*]   RFCOMM TTY support

<*>   BNEP protocol support                   //蓝牙网络封装协议,自组网支持

[*]   Multicast filter support                      //蓝牙多播,支持支持BNEP

[*]   Protocol filter support                       //蓝牙多播,支持支持支持BNEP

<*>   HIDP protocol support                   //基本支持协议

Bluetoothdevice drivers  --->

<*>HCI USB driver                                 //USB蓝牙模块支持

<*>HCIUART driver                               //基于串口,CF卡或PCMCIA的蓝牙

<*>HCI BlueFRITZ! USB driver

<*>HCI VHCI (Virtual HCI device) driver

其余的选项,根据自己的蓝牙设备进行调整。

2)移植完的bluez,把安装文件拷贝到板子上,只需要dbus和bluez的安装文件,总共应该不超过5M,我的在/usr/local/bluez,然后添加环境变量。

拷贝几个库文件,添加messagebus用户,还是参考刚才的wiki

  1. addgroup -S messagebus
  2. adduser -S messagebus -G messagebus

http://wiki.beyondlogic.org/index.php?title=Cross_Compiling_BlueZ_Bluetooth_tools_for_ARM

可以试试hciconfig, hcitool, dbus-deamon等工具是否正常,正常了就移植成功了。

板子内存紧张可以用nfs挂载的方式来调试,挂载好了,环境变量设置到挂载的路径就可以了。

先安装好nfs服务器

https://jingyan.baidu.com/article/e5c39bf5abc8f739d76033be.html

开发板挂载ubuntu,在ubuntu用户目录下的nfs目录中准备好文件

在开发板上挂载ubuntu
mkdir /mnt/bluez
#在开发板端挂载板子网卡,这里用的USB模拟的网卡,挂载到usb0,真实的网卡就不需要模拟这一步了。

modprobe g_multi.ko file=/dev/mmcblk0p5,/dev/mmcblk0p6 ro=0,0 luns=2 stall=0 removable=1,1 iSerialNumber=3000111
ifconfig usb0 192.168.10.2

在ubuntu端打开网卡
ifconfig enp0s20f0u2 192.168.10.6 netmask 255.255.255.0
ifconfig enp0s20f0u2 up 192.168.10.6
#在开发板端挂载ubuntu上的nfs服务器
mount -t nfs -o nolock 192.168.10.6:/home/dong/nfs /mnt
#umount -t nfs -a nolock 192.168.10.6:/home/dong/nfs /mnt

开发板添加环境变量
#add path
export PATH=/mnt/bluez/bin:$PATH
export LD_LIBRARY_PATH=/mnt/bluez/lib:$LD_LIBRARY_PATH

或者在/etc/profile里添加环境变量永久生效

export PATH=\
/bin:\
/sbin:\
/usr/bin:\
/usr/sbin:\
/usr/bin/X11:\
/usr/local/bin:\
/mnt/bluez/bin:\

export LD_LIBRARY_PATH=/mnt/bluez/lib:$LD_LIBRARY_PATH

source /etc/profile

创建并运行脚本文件bluez.init.sh,运行成功就可以用手机搜到BlueZ-5.18的蓝牙设备

  1. #power on
  2. echo > /sys/class/gpio/export
  3. echo out > /sys/class/gpio/gpio49/direction
  4. echo > /sys/class/gpio/gpio49/value
  5. sleep 0.2
  6. echo > /sys/class/gpio/gpio49/value
  7. sleep 0.2
  8.  
  9. #load firmware
  10. hciattach -s /dev/ttyS2 texas flow
  11.  
  12. hciconfig hci0 up
  13. sleep 0.1
  14. hciconfig hci0 iscan
  15. sleep 0.1
  16.  
  17. rm -rf /usr/local/bluez/var/run/dbus/pid
  18.  
  19. dbus-daemon --system
  20. sleep 0.2
  21. bluetoothd &
  22. sleep
  23. hciconfig hci0 iscan

有时候环境变量写到配置文件会失效,程序运行会从系统库目录/lib  /usr/lib查找库文件,不从我们配置的/mnt/bluez/lib目录里找

运行临时环境变量配置指令即可生效

export PATH=/mnt/bluez/bin:$PATH
export LD_LIBRARY_PATH=/mnt/bluez/lib:$LD_LIBRARY_PATH

3、python移植

新版本bluez的demo都是python写的,所以还需要把python也移植到板子上。
1)下载好Python-2.7.2.tgz和补丁文件Python-2.7.2-xcompile.patch
2)编译PC上运行的pgen
./configure

make python Parser/pgen

mv python hostpython

mv Parser/pgen Parser/hostpgen

make distclean

3)给Python-2.7.2打补丁
patch -p1 < Python-2.7.2-xcompile.patch

4)交叉编译,编译器arm-linux-gnueabihf-
CC=arm-linux-gnueabihf-gcc
CXX=arm-linux-gnueabihf-g++ AR=arm-linux-gnueabihf-ar
RANLIB=arm-linux-gnueabihf-ranlib ./configure --host=arm-linux-gnueabihf
--build=x86_64-linux-gnu --prefix=/home/dong/_install

chmod 777 ./setup.py

如果空间紧张,可以更改Makefile,不需要debug,去掉-g,优化等级调成-o2
#OPT=        -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes
OPT=        -DNDEBUG -fwrapv -O2 -Wall -Wstrict-prototypes

make
HOSTPYTHON=./hostpython HOSTPGEN=./Parser/hostpgen
BLDSHARED="arm-linux-gnueabihf-gcc -shared"
CROSS_COMPILE=arm-linux-gnueabihf- CROSS_COMPILE_TARGET=yes
HOSTARCH=arm-linux-gnueabihf BUILDARCH=x86_64-linux-gnu

make
install HOSTPYTHON=./hostpython BLDSHARED="arm-linux-gnueabihf-gcc
-shared" CROSS_COMPILE=arm-linux-gnueabihf- CROSS_COMPILE_TARGET=yes
prefix=/home/dong/_install

如果安装报错
python: Syntax error: word unexpected (expecting ")")
将install-sh文件第一行#!/bin/sh改成#!/bin/bash

5)把安装目录下的文件复制到arm设备上,并吧Python路径添加到PATH中,然后执行测试
python /usr/local/python/lib/python2.7/test/test___all__.py

我的板内存空间紧张,先用nfs挂载来调试

转自
http://blog.csdn.net/xiwenfuor/article/details/38384687
http://blog.sina.com.cn/s/blog_609b4c0d01012j5q.html

我移植完了,发现这个blog写得很简洁。

https://blog.csdn.net/qq_28351465/article/details/54406180

4、板载python调试

python的库文件很大,还是跟上面调试bluez一样,采用nfs来调试

开发板添加环境变量
#add path
export PATH=/mnt/python/bin:$PATH
export LD_LIBRARY_PATH=/mnt/python/lib:$LD_LIBRARY_PATH

或者在/etc/profile里添加环境变量永久生效

export PATH=\
/bin:\
/sbin:\
/usr/bin:\
/usr/sbin:\
/usr/bin/X11:\
/usr/local/bin:\
/mnt/bluez/bin:\
/mnt/python/bin:\

export LD_LIBRARY_PATH=/mnt/bluez/lib:$LD_LIBRARY_PATH

export LD_LIBRARY_PATH=/mnt/python/lib:$LD_LIBRARY_PATH

source /etc/profile

挂载后运行python –V就可以看到python的版本信息了。

python /mnt/python/lib/python2.7/test/test___all__.py
运行结果
Following
modules have no __all__ and have been ignored: ['DocXMLRPCServer',
'HTMLParser', 'SimpleXMLRPCServer', 'UserDict', 'UserList',
'_LWPCookieJar', '_MozillaCookieJar', '__phello__.foo', 'abc', 'an]
Following modules failed to be imported: ['ctypes.wintypes', 'dbhash', 'gzip', 'idlelib.AutoComplete']
ok

----------------------------------------------------------------------
Ran 1 test in 48.532s

OK

5、运行simple-agent 或者 BlueZ SPP Demo
[root@sama5d3x /mnt]# python simple-agent
Traceback (most recent call last):
  File "simple-agent", line 7, in <module>
    import dbus
ImportError: No module named dbus

缺了dbus模块
交叉编译dbus-python-1.2.4

折腾一天看见这个心碎了

https://www.zhihu.com/question/34573048

找了一圈,只能用buildroot来制作支持python的文件系统

http://www.at91.com/linux4sam/bin/view/Linux4SAM/BuildRootBuild

https://www.cnblogs.com/chencanjian/p/6060448.html

6、buildroot编译dbus-python库

进入buildroot根目录
make menuconfig
找到

dbus-python

gobject

其实不用像上面那样单独移植python也可以,就在buildroot里把python和需要的库都选上更方便,

buildroot还可以压缩库文件,还更省空间。

用yocto或者 OpenEmbedded来构建文件系统貌似也行,没有验证

 
make编译完就有了dbus-python库,运行python simple-agent,缺哪个库就拷贝哪个库,一共需要10几个吧。
库都不缺了,发现连接不上dbus.SystemBus()
  1. [root@sama5d3x /mnt]# python
  2. Python 2.7.2 (default, Jan 20 2018, 15:29:23)
  3. [GCC 4.7.3 20121205 (prerelease)] on linux4
  4. Type "help", "copyright", "credits" or "license" for more information.
  5. >>> from __future__ import absolute_import, print_function, unicode_literals
  6. >>> import gobject as GObject
  7. >>> import sys
  8. >>> import dbus
  9. >>> import dbus.service
  10. >>> import dbus.mainloop.glib
  11. >>> from optparse import OptionParser
  12. >>> dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
  13. <dbus.mainloop.NativeMainLoop object at 0x2ecc08>
  14. >>> bus = dbus.SystemBus()
  15. Traceback (most recent call last):
  16. File "<stdin>", line 1, in <module>
  17. File "/usr/lib/python2.7/site-packages/dbus/_dbus.py", line 194, in __new__
  18. File "/usr/lib/python2.7/site-packages/dbus/_dbus.py", line 100, in __new__
  19. File "/usr/lib/python2.7/site-packages/dbus/bus.py", line 122, in __new__
  20. dbus.exceptions.DBusException: org.freedesktop.DBus.Error.FileNotFound: Failed to connect to socket /var/run/dbus/system_bus_socket: No such file or directory

连不上dbus的socket,就差一口气了......

突然发现dbus-1.8.库编译的时候没打开--with-system-socket

参考http://www.linuxfromscratch.org/blfs/view/svn/general/dbus.html

  1. ./configure --prefix=/usr \
  2. --sysconfdir=/etc \
  3. --localstatedir=/var \
  4. --disable-doxygen-docs \
  5. --disable-xml-docs \
  6. --disable-static \
  7. --docdir=/usr/share/doc/dbus-1.8. \
  8. --with-console-auth-dir=/run/console \
  9. --with-system-pid-file=/run/dbus/pid \
  10. --with-system-socket=/run/dbus/system_bus_socket &&
  11. make

更改上面dbus-1.8.的编译配置,上面已经改过来了,重新编译,再运行配对例子

  1. [root@sama5d3x test]# hciconfig hci0 pscan
  2. [root@sama5d3x test]# hciconfig hci0 noauth
  3. [root@sama5d3x test]# python simple-agent
  4. Agent registered
  5. RequestConfirmation (/org/bluez/hci0/dev_E4_46_DA_6E_8D_85, )
  6. Confirm passkey (yes/no): yes
  7. [root@sama5d3x test]# cd ..
  8. [root@sama5d3x /mnt]# python SPP-loopback.py
  9. NewConnection(/org/bluez/hci0/dev_E4_46_DA_6E_8D_85, )
  10. received: aaa
  11. received: step by step
  12. received: BlueZ SPP OK !

配对simple-agent和蓝牙透传SPP-loopback.py都正常,再把bluez和python库裁剪,整理好就可以植入产品里了。

SPP-loopback.py蓝牙串口透传例子是intel的Edison模块的,也可以用在这里。

intel edison bluetooth guide 这个文档比较完整。

http://download.intel.com/support/edison/sb/edisonbluetooth_331704004.pdf

我整理的启动脚本 bluez_init.sh

  1. #power on
  2. echo > /sys/class/gpio/export
  3. echo out > /sys/class/gpio/gpio49/direction
  4. echo > /sys/class/gpio/gpio49/value
  5. sleep 0.2
  6. echo > /sys/class/gpio/gpio49/value
  7. sleep 0.2
  8.  
  9. #load firmware
  10. hciattach -s /dev/ttyS2 texas flow
  11. sleep
  12. hciconfig hci0 up
  13. sleep 0.1
  14. hciconfig hci0 iscan
  15. sleep 0.1
  16.  
  17. #add dbus dir
  18. rm -r /usr/local/bluez/var/run/dbus
  19. ln -s /run/dbus/ /usr/local/bluez/var/run/
  20. rm -rf /usr/local/bluez/var/run/dbus/pid
  21. mkdir /run/dbus
  22.  
  23. #boot bluez process
  24. dbus-daemon --system
  25. sleep
  26. bluetoothd &
  27. sleep
  28.  
  29. #run user app
  30. python simple-agent &
  31. sleep 0.1
  32. python SPP-loopback.py &
  33. sleep 0.1
  34. hciconfig hci0 name "bluez_test"
  35. hciconfig hci0 piscan

将bluez-5.18的simple-agent文件中配对认证注释掉,设备就不认证了

  1. def AuthorizeService(self, device, uuid):
  2. print("AuthorizeService (%s, %s)" % (device, uuid))
  3. #authorize = ask("Authorize connection (yes/no): ")
  4. #if (authorize == "yes"):
  5. # return
  6. #raise Rejected("Connection rejected by user")
  7. ...
  8. ...
  9.  
  10. def RequestConfirmation(self, device, passkey):
  11. print("RequestConfirmation (%s, %06d)" % (device, passkey))
  12. #confirm = ask("Confirm passkey (yes/no): ")
  13. #if (confirm == "yes"):
  14. set_trusted(device)
  15. # return
  16. #raise Rejected("Passkey doesn't match")
  17.  
  18. @dbus.service.method(AGENT_INTERFACE,
  19. in_signature="o", out_signature="")
  20. def RequestAuthorization(self, device):
  21. print("RequestAuthorization (%s)" % (device))
  22. #auth = ask("Authorize? (yes/no): ")
  23. #if (auth == "yes"):
  24. # return
  25. #raise Rejected("Pairing rejected")

给板子上电,挂载好bluez和python的库文件,然后运行上面的启动脚本 ./bluez.init.sh

[root@sama5d3x /root]# mount -t nfs -o nolock 192.168.10.6:/home/dong/nfs /mnt  
[root@sama5d3x /root]# cd /mnt/                                                 
[root@sama5d3x /mnt]# ./bluez.init.sh                                           
Found a Texas Instruments' chip!                                                
Firmware file : /lib/firmware/ti-connectivity/TIInit_11.8.32.bts                
Loaded BTS script version 1                                                     
Device setup complete                                                           
[root@sama5d3x /mnt]# Agent registered                                          
RequestConfirmation (/org/bluez/hci0/dev_E4_46_DA_6E_8D_85, 345760)             
NewConnection(/org/bluez/hci0/dev_E4_46_DA_6E_8D_85, 9)                         
received: step by step                                                          
received: step by step                                                          
received: step by step

7、python与c之间的交互

可以用的方式很多,共享内存,消息队列,管道,进程池或者直接封装接口互相调用函数。

搜一下就有了.下面是我找的共享内存机制

1) Python读取c语言进程的内存块

http://chl0000.iteye.com/blog/1915303

http://www.linuxidc.com/Linux/2012-03/57430.htm

2) python和c语言参数传递

c--->python
http://blog.csdn.net/JoeBlackzqq/article/details/10441017
http://blog.csdn.net/chenyulancn/article/details/8158168
python--->c
http://blog.csdn.net/mrcheny/article/details/79022973

3) 实例:导出python进程的数据

我这个项目需要导出python进程的数据给c进程处理

给c语言进程提供一个数据结构

bluetooth_data.c

  1. #include <stdio.h>
  2.  
  3. struct bluetooth_t{
  4. int status;
  5. char *buf;
  6. };
  7.  
  8. int bluetooth_cb(struct bluetooth_t bluetooth)
  9. {
  10. printf("bluetooth status:%d, bluetooth buf:%s \n", bluetooth.status,bluetooth.buf);
  11. return ;
  12. }

编译成so库文件

gcc/arm-linux-gnueabihf-gcc -o bluetooth_data.so -shared -fPIC bluetooth_data.c

然后python进程把需要的数据写到上面的数据结构

data_test.py

  1. #!/usr/bin/python
  2. import ctypes
  3. from ctypes import *
  4.  
  5. class bluetooth(Structure):
  6. _fields_=[('status',c_int),('buf',c_char_p)]
  7.  
  8. if __name__ == "__main__":
  9.  
  10. func = ctypes.cdll.LoadLibrary("./bluetooth_data.so")
  11.  
  12. s = bluetooth()
  13. s.status = 1
  14. s.buf = bytes('hello,world')
  15. func.bluetooth_cb(s)

运行python data_test.py就可以打印出导出的数据

bluetooth status:1, bluetooth buf:hello,world.

8、bluez的BLE工作模式

只有bluez-5.xx以上版本才支持低功耗模式,配置跟普通模式有细微差别

我配置的BLE模式启动脚本 bluez_le_init.sh

  1. #power on
  2. echo > /sys/class/gpio/export
  3. echo out > /sys/class/gpio/gpio49/direction
  4. echo > /sys/class/gpio/gpio49/value
  5. sleep 0.2
  6. echo > /sys/class/gpio/gpio49/value
  7. sleep 0.2
  8.  
  9. #load firmware
  10. hciattach -s /dev/ttyS2 texas flow
  11. sleep
  12. hciconfig hci0 up
  13. sleep 0.1
  14. hciconfig hci0 iscan
  15. sleep 0.1
  16.  
  17. #add dbus dir
  18. rm -r /usr/local/bluez/var/run/dbus
  19. ln -s /run/dbus/ /usr/local/bluez/var/run/
  20. rm -rf /usr/local/bluez/var/run/dbus/pid
  21. mkdir /run/dbus
  22.  
  23. #boot bluez process
  24. dbus-daemon --system
  25. sleep
  26. bluetoothd &
  27. sleep
  28.  
  29. #run user app
  30. python simple-agent &
  31. sleep 0.1
  32.  
  33. if false ; then
  34. #Bluetooth SPP
  35. python SPP-loopback.py &
  36. else
  37. #Bluetooth profile
  38. hciconfig hci0 up
  39. sleep 0.1
  40. hciconfig hci0 leadv
  41. fi
  42.  
  43. sleep 0.1
  44. hciconfig hci0 name "bluez_test"
  45. hciconfig hci0 piscan

用了个

if false ; then

...

else

...

fi

把普通模式和BLE模式分开

给板子上电后运行./bluez.le.init.sh

找个蓝牙4.0的工具( 我用的BLE Tool )就能扫到BlueZ-5.18的设备, 读几个自带的特征值profile都正常。

9、蓝牙NFS挂载模式应用(nfs_debug)

首次运行需要配置相关系统参数

1)#配置内核蓝牙选项

2)#添加进程消息通道
addgroup -S messagebus
adduser -S messagebus -G messagebus

3#添加lp
vi /etc/group
lp:x:7:

4)#配置网卡
modprobe g_multi.ko file=/dev/mmcblk0p5,/dev/mmcblk0p6 ro=0,0 luns=2 stall=0 removable=1,1 iSerialNumber=3000111
ifconfig usb0 192.168.10.2

5)在ubuntu端打开网卡
不同主机生成的网卡名称可能不一样,ifconfig查看,这个是我的台式机,下面那个是我的笔记本
sudo ifconfig enp0s20f0u2 192.168.10.6 netmask 255.255.255.0
sudo ifconfig enp0s20f0u2 up 192.168.10.6

sudo ifconfig enp0s20f0u4 192.168.10.6 netmask 255.255.255.0
sudo ifconfig enp0s20f0u4 up 192.168.10.6

6)#在开发板端挂载ubuntu上的nfs服务器
mount -t nfs -o nolock 192.168.10.6:/home/dong/nfs /mnt/nfs
#umount -t nfs -a nolock 192.168.10.6:/home/dong/nfs /mnt/nfs

7)#添加环境变量

export PATH=\
/bin:\
/sbin:\
/usr/bin:\
/usr/sbin:\
/usr/bin/X11:\
/usr/local/bin:\
/mnt/nfs/bluez/bin:\
/mnt/nfs/python/bin:\

...

export LD_LIBRARY_PATH=/mnt/nfs/bluez/lib:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=/mnt/nfs/python/lib:$LD_LIBRARY_PATH

source /etc/profile

8)添加bluez配置文件
#cp -r /mnt/bluez /usr/local/
#cp -r /mnt/python /usr/local/
cp -r config/bluez /usr/local/

9) 启动蓝牙应用
./bluez.init.sh

10、蓝牙正式应用(readme)

蓝牙文件系统构建:

1) 配置内核蓝牙选项

2) 添加进程消息通道
addgroup -S messagebus
adduser -S messagebus -G messagebus

3) 添加lp
vi /etc/group
lp:x:7:

4) 拷贝库文件
cp -r bluez /usr/local/                                    
cp -r python /usr/local/

5)拷贝应用程序
cp bluez.init.sh SPP-loopback.py /usr/local/project/
cp -r test /usr/local/project/

6)添加dbus软链接
rm -r /usr/local/bluez/var/run/dbus
ln -s /run/dbus/ /usr/local/bluez/var/run/

7)启动蓝牙进程bluez_init.sh

三、Bluetooth Audio ALSA Backend

https://github.com/Arkq/bluez-alsa

四、BLE4.0 Gatt-server

除了bluez的test目录python脚本 example-gatt-server(依赖的组件比较多,可能运行起来有点困难)

还有两种方案添加gatt自定义服务,都是开源的

一种是用bleno库,一种是go-server

我用的芯片不支持完整的BLE4.0,不能自定义用户profile 和 gatt service

一般完整支持BLE4.0或以上的芯片都是带flash的,需要更改蓝牙协议栈固件,能够作为IoT场景应用的蓝牙IC除了少部分通用芯片,大部分都是定制的专用芯片,像csr1000系列,TI的cc25xx cc26xx系列,nordic的rf51xx rf52xx系列等,都需要用厂商的专用工具来配置profile和gatt service.

下面参考文献是我收集的蓝牙自定义gatt-server方案和应用实例。

参考文献

1)RPi Bluetooth LE

2)用树莓派玩转蓝牙

3)A Node.js module for implementing BLE (Bluetooth Low Energy) peripherals

4)Package gatt provides a Bluetooth Low Energy GATT implementation

5)玩转BLE(3)_使用微信蓝牙精简协议伪造记步数据

6)Implementation of BLE peripheral using bleno

7)Python BLE GATT Server (peripheral)

8)Standalone D-Bus-based BlueZ BLE GATT server for C/C++

9)A custom Prosthetic GATT profile BLE Server / Peripheral implementation for prototyping and GA integration testing.

越折腾越深入,工作上做的产品最多也就用到这些内容,你愿意将业余时间花在蓝牙协议栈上面,深挖到底吗?对不起,我不舍得,就此打住!

最后总结:从0到调试完成,整个过程需要点耐心,我前面因为太急躁导致多做了不少无用功,欲速则不达。

end

BlueZ的更多相关文章

  1. 《Bluez 》Beta版强势回归!!!

    Bluez .Beta 巅峰塔防 强势回归! Z.XML为您呈现 经过了第二轮迭代,我们骄傲的宣布,Bluez Beta版本,正式发布. 下载地址:-> 第二轮的迭代是辛苦的,但是不同于其他队伍 ...

  2. Bluez alpha版震撼发布!

    经过Z.XML团队所有成员的不懈努力,我们的Bluez alpha版成功完成了!现在我们宣布:Bluez alpha版正式发布! 首先我们来向大家介绍下我们这个游戏: 这是一款即时RPG塔防类游戏.在 ...

  3. 【转】Android bluetooth介绍(二): android blueZ蓝牙代码架构及其uart 到rfcomm流程

    原文网址:http://blog.sina.com.cn/s/blog_602c72c50102uzoj.html 关键词:蓝牙blueZ  UART  HCI_UART H4  HCI  L2CAP ...

  4. Bluez SPP实现代码分析(转)

    源:http://blog.csdn.net/walkingman321/article/details/7218705 本文分析蓝牙协议栈中蓝牙转串口(SPP)部分的实现. 1.  基本概念 Blu ...

  5. [BlueZ] 2、使用bluetoothctl搜索、连接、配对、读写、使能notify蓝牙低功耗设备

    星期三, 05. 九月 2018 02:03上午 - beautifulzzzz 1.前言 上一篇讲了如何编译安装BlueZ-5,本篇主要在于玩BlueZ,用命令行去操作BLE设备: [BlueZ] ...

  6. [BlueZ] 1、Download install and use the BlueZ and hcitool on PI 3B+

    星期日, 02. 九月 2018 11:58下午 - beautifulzzzz 1. Introduction Bluez is the default Bluetooth protocol sta ...

  7. Bluez相关的各种tools的使用

    7.1        Bccmd Bccmd是用来和CSR的芯片进行BCCMD(Bluecore command protocol)通讯的一个工具.BCCMD并非蓝牙协议栈的标准,而是CSR芯片的专属 ...

  8. linux bluez

    Linux下开放的蓝牙协议栈主要包括IBM公司的BlueDrekar,Nokia公司的Affix, Axis公司的OpenBT和官方协议栈BlueZ.我们主要对Bluez进行探讨. BlueZ基础代码 ...

  9. linux下蓝牙开发(bluez应用)

    编译blueZ-5.25 需要先编译安装以下包: bluez-libs-3.36.tar.gz expat-2.1.0.tar.gz dbus-1.10.0.tar.gz glib-2.26.1.ta ...

随机推荐

  1. hdu6125 Free from square 分组背包+状态压缩

    /** 题目:hdu6125 Free from square 链接:http://acm.hdu.edu.cn/showproblem.php?pid=6125 题意: 从不大于n的所有正整数中选出 ...

  2. resize2fs命令出现这个错误“resize2fs: Operation not permitted While trying to add group #6656” 有数据的会丢数据

    1. resize2fs命令出现这个错误“resize2fs: Operation not permitted While trying to add group #6656”,并且在/var/log ...

  3. 浅谈Facebook的服务器架构(组图)

    导读:毫无疑问,作为全球最领先的社交网络,Facebook的高性能集群系统承担了海量数据的处理,它的服务器架构一直为业界众人所关注.CSDN博主yanghehong在他自己最新的一篇博客< Fa ...

  4. ThinkPHP项目笔记之RBAC(权限相关视频讲解篇

    感谢互联网,只要你愿意找,没有找不到的免费资源 网址:http://www.studyfox.cn/143.html

  5. 通过代码注册COM、DLL组件

    注册代码如下:  C++ Code  1234567891011121314151617181920212223242526272829303132333435363738   // //====== ...

  6. Appium移动自动化测试(一)--工具软件安装

    Appium移动自动化测试(一)--工具软件安装 详情参考-- http://www.cnblogs.com/fnng/p/4552438.html 第一节  安装node.js Appium 官方网 ...

  7. windows 2003 发布遇到问题---分析器错误消息: 未能加载类型“YWPT.MvcApplication”。

    问题如下: “/”应用程序中的服务器错误. ------------------------------------------------------------------------------ ...

  8. 分页技巧_抽取出公共的分页用的Service方法

    分页技巧_抽取出公共的分页用的Service方法 TopicAction.java ForumAction.java 放在父类中DaoSupport.java DaoSupportImpl.java ...

  9. Maven编译失败,提示No compiler is provided in this enviroment. Perhaps you are running on a JRE rathen a JDK ?

    用maven对项目进行构建时,提示No compiler is provided in this enviroment. Perhaps you are running on a JRE rathen ...

  10. Objective-C代码学习大纲(6)

    2011-05-11 14:06 佚名 otierney 字号:T | T 本文为台湾出版的<Objective-C学习大纲>的翻译文档,系统介绍了Objective-C代码,很多名词为台 ...