我整天都在尝试解决问题,做了很多研究,尝试了许多不同的方法,但是没有一个起作用。我目前有一个使用bluepy连接到蓝牙BLE设备的代码,当它连接正常时,但是有时它无法连接并且不会出错,只是在[00:00:00]行中被吸住了: 00:00]正在连接,并且不会显示在“例外”中。当我发送新命令时,有时可以正常工作,但是由于我没有收到错误或任何信息,因此我不确定何时需要发送新命令。
下面是代码:
#!/usr/bin/env python
from bluepy import *
import paho.mqtt.client as mqtt
import struct
### Variables
mqtt_client = ""
mqtt_port =
mqtt_user = ""
mqtt_password = ""
mqtt_path = ""
#### Don't edit below here
open = "\x00\xff\x00\x00\x9a\x0d\x01\x00\x96"
close = "\x00\xff\x00\x00\x9a\x0d\x01\x64\xf2"
def shade_command(fble,fcmd):
try:
print "["+ fble + "] Connecting"
dev = btle.Peripheral(fble)
print "["+ fble + "] Connected!"
chs = dev.getcharacteristics()
for ch in chs:
if ch.uuid == "0000fe51-0000-1000-8000-00805f9b34fb":
ch.write(fcmd)
dev.disconnect
print "["+ fble + "] Disconnected"
except:
print "["+ fble + "] Error Connecting"
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client,userdata,flags,rc):
print("Connected to MQTT with result code "+str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe(mqtt_path + "/#")
# The callback for when a PUBLISH message is received from the server.
def on_message(client,msg):
if msg.payload == "open":
address = msg.topic.replace(mqtt_path + "/","")
result = shade_command(address,open)
if result == True:
print msg.topic + "/status"
client.publish(msg.topic + "/status","on",qos=0,retain=False)
if msg.payload == "close":
address = msg.topic.replace(mqtt_path + "/",close)
if result == True:
client.publish(msg.topic + "/status","off",retain=False)
print msg.topic + "/status"
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set(mqtt_user,password=mqtt_password)
client.connect(mqtt_client,mqtt_port,60)
问题在这里发生:
def shade_command(fble,fcmd):
try:
print "["+ fble + "] Connecting"
dev = btle.Peripheral(fble)
print "["+ fble + "] Connected!"
chs = dev.getcharacteristics()
for ch in chs:
if ch.uuid == "0000fe51-0000-1000-8000-00805f9b34fb":
ch.write(fcmd)
dev.disconnect
print "["+ fble + "] Disconnected"
except:
print "["+ fble + "] Error Connecting"
当我尝试连接到MAC地址并且不起作用时,我没有收到错误消息,只是在这段代码之后停下来:
print "["+ fble + "] Connecting"
dev = btle.Peripheral(fble)
我最后看到的是[00:00:00:00:00]正在连接,什么都没有!我期待看到例外代码。
下面是一个输出示例,当我发送MQTT命令时,它首先尝试连接,但是什么也没有发生,它只是停止了,而不是我发送了另一个命令,并且它起作用了,我知道它在显示“ Connecting”,“连接的!”和“已断开连接”
[02:B3:CD:3D:C5:34] Connecting
[02:B3:CD:3D:C5:34] Connecting
[02:B3:CD:3D:C5:34] Connected!
[02:B3:CD:3D:C5:34] Disconnected
编辑1:
试图使用下面的除外代码,但不起作用:
except btle.BTLEException as e:
编辑2:
现在感谢@hardillb,我知道paho mqtt是捕获错误并忽略它们的人,我添加了这段代码,现在我可以看到何时发生错误:
def on_log(client,level,buff): # mqtt logs function
print buff
client.on_log = on_log
当我遇到错误时,它显示如下:
Caught exception in on_message: global name 'traceback' is not defined