树莓派使用蓝牙设置wifi网络

在树莓派使用过程中,很多人都有遇到过这样的问题,经常由于工作场所变化,在无显示器和鼠标的情况下无法方便快捷对树莓派设置wifi网络。

在物联网场景下,成熟的方案是使用蓝牙为设备设置网络,在本教程中,我想向您展示一种简单的方法,可以通过蓝牙仅使用Android手机为Raspberry Pi配置Wi-Fi网络。

所需材料

首先,您需要:

  • 树莓派3
  • Android手机
  • Python脚本

1 在Raspbian上安装Bluez

首先从Raspbian终端输入以下命令,安装Python蓝牙库Bluez:


$ sudo apt-get install python-bluez

2 启动Bluetooh 守护程序

通过输入以下命令来编辑 /etc/systemd/system/dbus-org.bluez.service


$ sudo nano /etc/systemd/system/dbus-org.bluez.service

并修改 ExecStart 参数
ExecStart = / usr / lib / bluetooth / bluetoothd –C

3 加载串口配置


$ sudo sdptool add SP

4 重启树莓派


$ sudo reboot

5 将Pi的蓝牙与Android配对

打开手机的蓝牙,然后将手机与Raspberry Pi配对。接下来,在您的Pi上输入:


$ bluetoothctl
power on
discoverable on
scan on

您的手机将出现在可用设备列表中。信任并配对。


$ trust <PHONE_ADDRESS>
$ pair  <PHONE_ADDRESS>

要退出Bluetooth ctl,请输入quit命令:

如果发现可以使用Raspbian的UI轻松设置蓝牙,则也可以跳过上述设置。通过

6 蓝牙配对后,通过键入nano命令并复制/粘贴源代码将Python脚本直接添加到Raspbian中并执行:

#!/usr/bin/env python
import os
from bluetooth import *
from wifi import Cell, Scheme
import subprocess
import time
wpa_supplicant_conf = "/etc/wpa_supplicant/wpa_supplicant.conf"
sudo_mode = "sudo "
def wifi_connect(ssid, psk):
   # write wifi config to file
   cmd = 'wpa_passphrase {ssid} {psk} | sudo tee -a {conf} > /dev/null'.format(
           ssid=str(ssid).replace('!', '\!'),
           psk=str(psk).replace('!', '\!'),
           conf=wpa_supplicant_conf
       )
   cmd_result = ""
   cmd_result = os.system(cmd)
   print cmd + " - " + str(cmd_result)

   # reconfigure wifi
   cmd = sudo_mode + 'wpa_cli -i wlan0 reconfigure'
   cmd_result = os.system(cmd)
   print cmd + " - " + str(cmd_result)

   time.sleep(10)

   cmd = 'iwconfig wlan0'
   cmd_result = os.system(cmd)
   print cmd + " - " + str(cmd_result)

   cmd = 'ifconfig wlan0'
   cmd_result = os.system(cmd)
   print cmd + " - " + str(cmd_result)

   p = subprocess.Popen(['hostname', '-I'], stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE)

   out, err = p.communicate()

   if out:
       ip_address = out
   else:
       ip_address = "<Not Set>"
   return ip_address

def ssid_discovered():
   Cells = Cell.all('wlan0')
   wifi_info = 'Found ssid : \n'
   for current in range(len(Cells)):
       wifi_info +=  Cells[current].ssid + "\n"
   wifi_info+="!"
   print wifi_info
   return wifi_info
def handle_client(client_sock) :
   # get ssid
   client_sock.send(ssid_discovered())
   print "Waiting for SSID..."
   ssid = client_sock.recv(1024)
   if ssid == '' :
       return

   print "ssid received"
   print ssid

   # get psk
   client_sock.send("waiting-psk!")
   print "Waiting for PSK..."
   psk = client_sock.recv(1024)
   if psk == '' :
       return

   print "psk received"
   print psk

   ip_address = wifi_connect(ssid, psk)
   print "ip address: " + ip_address
   client_sock.send("ip-address:" + ip_address + "!")
   return
try:
   while True:
       server_sock=BluetoothSocket( RFCOMM )
       server_sock.bind(("",PORT_ANY))
       server_sock.listen(1)

       port = server_sock.getsockname()[1]

       uuid = "815425a5-bfac-47bf-9321-c5ff980b5e11"
       advertise_service( server_sock, "RPi Wifi config",
                          service_id = uuid,
                          service_classes = [ uuid, SERIAL_PORT_CLASS ],
                          profiles = [ SERIAL_PORT_PROFILE ])


       print "Waiting for connection on RFCOMM channel %d" % port

       client_sock, client_info = server_sock.accept()
       print "Accepted connection from ", client_info

       handle_client(client_sock)

       client_sock.close()
       server_sock.close()

       # finished config
       print 'Finished configuration\n'
except (KeyboardInterrupt, SystemExit):
   print '\nExiting\n'

接下来,您可以运行脚本

$ chmod +x run.py
$ sudo python run.py

7 现在您需要打开android 串口调试工具(BluetoothSerial)设置WIFI。

在蓝牙配对设备中选择Raspberry Pi。输入SSID,PSK,然后点击开始配置按钮。在几秒钟内,您的Raspberry Pi的Wi-Fi应该会连接。

现在你可以通过蓝牙设置你的树莓派网络了,你也可以把脚本加到启动项,这样保证每次开机自动启动设置WIFI网络的 蓝牙服务

8 编辑/etc/rc.local 添加启动时运行此脚本

(sleep 10;/path/to/script/./run.py)&

😊done ...