萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Linux 藍牙功能完整操作指南:hcitool、rfcomm、rfkill 實戰

Linux 藍牙子系統成熟完善,透過 bluez 套件提供 hcitool、bluetoothctl、rfcomm、rfkill 等工具,支援裝置發現、配對、序列埠模擬、音訊串流、軟硬體開關控制。本文從硬體確認到實際連線、除錯全流程實作。

一、硬體確認與核心模組


# 列出 USB 裝置,尋找 Bluetooth 控制器
lsusb
# 輸出範例:Bus 001 Device 004: ID 8087:0a2b Intel Corp. Bluetooth wireless interface

# 查看核心模組
lsmod | grep -i bluetooth
# btusb, btrtl, btintel, btbcm, bluetooth

# 查看 HCI 介面
hciconfig
# hci0: Type: Primary  Bus: USB  BD Address: XX:XX:XX:XX:XX:XX  UP RUNNING

二、藍牙服務管理


# systemd 管理
systemctl status bluetooth
systemctl enable --now bluetooth

# 檢查 RFKill 狀態(軟/硬阻擋)
rfkill list
# 0: hci0: Bluetooth  Soft blocked: no  Hard blocked: no

rfkill 控制


rfkill block bluetooth    # 軟關閉
rfkill unblock bluetooth  # 軟開啟
rfkill block all          # 關閉所有無線
rfkill unblock all        # 開啟所有無線

若開機無法連線、硬體開關正常但 rfkill list 顯示 Hard blocked: yes,請檢查筆電物理開關、BIOS 設定、rfkill 核心參數。

三、裝置掃描與配對(bluetoothctl 推薦)

現代標準工具:bluetoothctl 互動式介面,取代舊式 hcitool/hciattach。


bluetoothctl
[bluetooth]# power on
[bluetooth]# agent on
[bluetooth]# default-agent
[bluetooth]# scan on
Discovery started
[NEW] Device AA:BB:CC:DD:EE:FF My Phone
[bluetooth]# pair AA:BB:CC:DD:EE:FF
Attempting to pair with AA:BB:CC:DD:EE:FF
[CHG] Device AA:BB:CC:DD:EE:FF Paired: yes
[bluetooth]# trust AA:BB:CC:DD:EE:FF
[bluetooth]# connect AA:BB:CC:DD:EE:FF
Connection successful
[bluetooth]# quit

四、舊式工具流程(hcitool + rfcomm,相容舊腳本)

1. 掃描裝置


hcitool scan
# Scanning ...
#   AA:BB:CC:DD:EE:FF  My Phone

2. 綁定 RFCOMM 序列埠


# 建立 /dev/rfcomm0 對應目標裝置
sudo rfcomm bind 0 AA:BB:CC:DD:EE:FF
# 或指定通道
sudo rfcomm bind 0 AA:BB:CC:DD:EE:FF 1

3. 連線測試


# 簡單測試:cat 會阻塞等待資料
sudo cat > /dev/rfcomm0
# 目標裝置彈出配對碼輸入框,輸入一致即配對成功

4. 釋放綁定


sudo rfcomm release 0
# 或全部釋放
sudo rfcomm release all

五、常見應用場景

場景關鍵設定/工具
藍牙音訊 (A2DP/HFP)bluez-alsa / pipewire / pulseaudio-module-bluetooth
序列埠通訊 (SPP)rfcomm bind → /dev/rfcomm0 → minicom/screen/Python pyserial
檔案傳輸 (OBEX)bluetoothctl + obexctl / blueman GUI
鍵盤/滑鼠 (HID)自動配對,bluetoothctl trust 後自動重連
網路共享 (PAN/NAP)bt-network / NetworkManager 藍牙共用

六、除錯檢查清單

  1. rfkill list 確認無硬/軟阻擋。
  2. systemctl status bluetooth 服務運行中。
  3. hciconfig hci0 up 介面啟動(bluetoothctl power on 同效)。
  4. dmesg -T | grep -i bluetooth 查看核心日誌錯誤。
  5. btmon 抓取 HCI 封包分析(需 root)。
  6. 配對失敗:刪除 /var/lib/bluetooth/ 下舊金鑰、目標裝置移除配對記錄、重試。
copyright © 萬盛學電腦網 all rights reserved