首页 > 解决方案 > 无法使用 Python 将 MQTT 消息存储到 SQL Server(Paho 客户端)中

问题描述

我正在尝试使用 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)

Éexpected output is sensor_handle 用于执行消息并将消息存储到数据库中。实际输出是仅打印了 on_message 中的打印 message.topic 和 message.payload 语句,但不执行 sensor_handler。任何帮助将不胜感激。

谢谢

标签: sql-serverpython-2.7mqttpaho

解决方案


推荐阅读