【问题标题】:Why my error is not getting catch by except?为什么我的错误没有被except捕获?
【发布时间】:2019-11-12 23:37:25
【问题描述】:

我整天都在尝试解决这个问题,做了很多研究,尝试了很多不同的方法,但都没有奏效。我目前有一个代码可以使用 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, userdata, 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 + "/", "")
        result = shade_command(address, close)
        if result == True:
          client.publish(msg.topic + "/status", "off", qos=0, 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 命令时它首先尝试连接,但没有任何反应,它只是停止,然后我发送了另一个命令并且它有效,我知道它在显示“正在连接”时有效,“连接的!”和“断开连接”

[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, userdata, level, buff):  # mqtt logs function
    print buff

client.on_log = on_log

出现错误时显示如下:

Caught exception in on_message: global name 'traceback' is not defined

【问题讨论】:

  • 您应该允许显示错误以便能够对其进行调试。请删除except 并运行它直到它坏掉。然后看看是什么错误并从那里开始工作。这是我们应该避免使用裸except 并同时指定异常类的原因之一。错误是一件好事,必须存在才能帮助您调试代码并避免静默失败。
  • 欢迎来到 StackOverflow。见minimal, reproducible example。在您发布 MRE 代码并准确说明问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中并重现您指定的问题。您的代码有几个异常,包括未定义的符号和您不使用的循环。
  • 最重要的是,您认为什么会引发运行时异常让您捕获?这个例外真的出现了吗?您的调试跟踪在哪里 - 插入一个或两个 print 语句来跟踪您的进度和值。
  • break 后面的return True 有什么意义?无法到达。
  • 根据本文档,您没有正确捕获异常。 programcreek.com/python/example/97794/bluepy.btle.BTLEException

标签: python error-handling bluetooth-lowenergy mqtt


【解决方案1】:

谢谢 hardillb 看起来在函数之外有 try/except 就可以了!

新的代码是这样的:

功能:

def shade_command(fble, fcmd):
    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"

调用函数:

def on_message(client, userdata, msg):
    if msg.payload == "open":
        try:
          address = msg.topic.replace(mqtt_path + "/", "")
          result = shade_command(address, open)
          print msg.topic + "/status"
          client.publish(msg.topic + "/status", "on", qos=0, retain=False)
        except:
          print "Error"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-16
    • 2012-01-22
    相关资源
    最近更新 更多