在RaspberryPi上使用python3通过蓝牙发送字符串

时间:2018-06-22 07:26:13

标签: python-3.x bluetooth raspberry-pi3

我正在尝试通过蓝牙从笔记本电脑向我的Raspberry Pi 3(RP)发送字符串。我似乎无法可靠地连接到我的RP。当我使用bluetoothctl并将可发现的设置更改为开时,在笔记本电脑甚至找不到RP之前,我可以连接两次。每当我想连接两次时,我都必须重新启动并切换到Discoverable。

  

服务器代码

import bluetooth as BLE
import gpiozero as IO

led = IO.LED(2)

port = 0

server_sock = BLE.BluetoothSocket(BLE.RFCOMM)
server_sock.bind(("", port))
server_sock.listen(1)

name = "Raspbian"

print("Awaiting connection...")

BLE.advertise_service(server_sock, name)

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

while True:
    data = client_sock.recv(1024)

    print(data)

    if data == "on":
        led.on()

print("Disconnected from ", client_info)

client_sock.close()
server_sock.close()
  

客户代码

import sys
import bluetooth as BLE

service_matches = BLE.find_service(name="Raspbian")
# uuid = SERIAL_PORT_CLASS )

if len(service_matches) == 0:
    print("Service not found")
    sys.exit(0)

first_match = service_matches[0]
port = first_match["port"]
name = first_match["name"]
host = first_match["host"]

print("connecting ...")

sock = BLE.BluetoothSocket(BLE.RFCOMM)
sock.connect((host, port))

while True:
    data = str(input("Input: "))
    sock.send(data)
    if data == "end":
        break

sock.close()

0 个答案:

没有答案