樹莓派開發筆記(十一):藍牙的使用,BlueZ協議(雙樹莓探測rssi並通過藍牙互傳獲取的rssi信號強度)

  • 2020 年 12 月 11 日
  • 筆記

若該文為原創文章,轉載請註明原文出處
本文章博客地址://blog.csdn.net/qq21497936/article/details/110940484
長期持續帶來更多項目與技術分享,諮詢請加QQ:21497936、微信:yangsir198808
紅胖子(紅模仿)的博文大全:開發技術集合(包含Qt實用技術、樹莓派、三維、OpenCV、OpenGL、ffmpeg、OSG、單片機、軟硬結合等等)持續更新中…(點擊傳送門)

 

前話

  接下來介紹樹莓派藍牙模塊的開發,使用的協議為bluez。

 

ssh遠程登錄到樹莓派

 

Demo:藍牙探測信號rssi強度,並發送給服務器

  在這裡插入圖片描述

  客戶端bob,服務器alice,探測兩方的rssi,並傳送給服務器alice
  在這裡插入圖片描述

  在這裡插入圖片描述
  在這裡插入圖片描述

 

Bluez

簡介

  BlueZ是官方Linux Bluetooth棧,由主機控制接口(Host Control Interface,HCI)層、Bluetooth協議核心、邏輯鏈路控制和適配協議(Logical Link Control and Adaptation Protocol,L2CAP)、SCO 音頻層、其他 Bluetooth 服務、用戶空間後台進程以及配置工具組成。
BlueZ由許多單獨的模塊組成:

  • 藍牙內核子系統核心
  • L2CAP和SCO音頻內核層
  • RFCOMM,BNEP,CMTP和HIDP內核實現
  • HCI UART,USB,PCMCIA和虛擬設備驅動程序
  • 通用藍牙和SDP庫和守護程序
  • 配置和測試實用程序
  • 協議解碼和分析工具
 

搭建Bluez

步驟一:安裝bluez

sudo apt-get install bluez
 

藍牙明命令行hciconfig/hcitool的使用

檢查藍牙設備是否加載成功

hciconfig

  在這裡插入圖片描述

打開藍牙

sudo hciconfig hci0 up

  在這裡插入圖片描述

掃描藍牙

sudo hciconfig iscan

  在這裡插入圖片描述

藍牙命令行工具bluetoothctl

  (注意:不好用,顯示的都是mac地址,而且中文亂碼,周圍藍牙多,根本分不清楚)

啟動藍牙程序

bluetoothctl

  在這裡插入圖片描述

啟動/關閉藍牙電源

power on/off

  在這裡插入圖片描述

獲取要配對設備的MAC地址

  在這裡插入圖片描述
  電腦上的藍牙,先打開:
  在這裡插入圖片描述

 

pybluez使用

sudo python3 -m pip install pybluez

關鍵源碼

server.py

# -*-coding: utf-8 -*-
from bluetooth import *
import sys
import time
import os
import struct
import bluetooth._bluetooth as bluez
import bluetooth

global hostRssi

os.system("bluetoothctl power on")

# 獲取服務,通過uuid查找目標服務
#uuid = "63078d70-feb9-lle7-9812-dca90488bd22"
#os.system("bluetoothctl discoverable on")
dstuuid   = "11111111-1111-1111-1111-111111111111"
localuuid = "22222222-2222-2222-2222-222222222222"

print("本地服務器,搜索客戶端藍牙rssi")
...
data = client.recv(1024)
print (data)
client.close()

bluetooth_sock.close()

client.py

from bluetooth import *
import sys
import time
import os
import struct
import bluetooth._bluetooth as bluez
import bluetooth

global hostRssi

#開啟藍牙可見
os.system("bluetoothctl power on")
os.system("bluetoothctl discoverable on")
dstuuid   = "22222222-2222-2222-2222-222222222222"
localuuid = "11111111-1111-1111-1111-111111111111"

bluetooth_sock=BluetoothSocket(RFCOMM)
bluetooth_sock.bind(("",PORT_ANY))
bluetooth_sock.listen(1)
...
 data = "server:" + str(hostRssi) + ", client:" + str(clientRssi)
...
 

入坑

入坑一:打開藍顏失敗

在這裡插入圖片描述

sudo vim /lib/systemd/system/bluetooth.service

  修改文件內容

#ExecStart=/usr/lib/bluez5/bluetooth/bluetoothd
ExecStart=/usr/lib/bluez5/bluetooth/bluetoothd -E -C

&emso;&emso;然後重啟服務

sudo sdptool add SP
sudo systemctl daemon-reload
sudo systemctl restart bluetooth
sudo sdptool browse local

入坑二:「no advertisable device」

  在這裡插入圖片描述
  原因:由於藍牙不可見導致

 
 

若該文為原創文章,轉載請註明原文出處
本文章博客地址://blog.csdn.net/qq21497936/article/details/110940484