我正在尝试使用Python将MQTT消息发送到SQL Server。为了提供一些背景信息,我正在模拟传感器读数,将其发布到“ iot.eclipse.org”,并使用Paho Client进行订阅。在订阅消息的代码中,如下所示,我正在调用sensor_handler,它使用message.topic和message.payload作为其参数。但是,在执行时,将打印打印消息,但是不执行sensor_handler函数。
我尝试单独执行sensor_handler(使用简单的sql查询),并且似乎运行良好。我认为问题出在on_message()函数中,但是我不确定问题出在哪里,为什么产生以及如何解决。
import paho.mqtt.client as mqtt
from storeInDatabase import sensor_handler
broker = "iot.eclipse.org"
broker_port = 1883
MQTT_Topic_Room1 = "Building/Room_1"
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+rc)
def on_message(client, userdata, message):
#print("Hallo I have the massage: "+message.payload.decode())
print "" + message.topic.decode()
#the following line is not executed but the prints are executed
sensor_handler(message.topic.decode(), message.payload.decode())
print "" + message.payload.decode()
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(broker, broker_port)
client.subscribe(MQTT_Topic_Room1)
client.loop_forever()
#-----------------------------------------------------------
#Temp_Humidity_Handler(data) parses json data and stores them in the
# sql server table
#------------------------------------------------------------
def sensor_handler(Topic, data):
if Topic == "Building\Room_1":
Temp_Humidity_Handler(data)
预期的输出是sensor_handle,以执行并将消息存储到数据库中。实际的输出是仅打印正在打印message.topic和message.payload的on_message中的打印语句,但不执行sensor_handler。任何帮助将不胜感激。
谢谢