与多个客户端的MQTT通信

时间:2018-10-01 13:05:24

标签: python mqtt

我正在实现MQTT客户在推车,电梯和移动设备之间的通信。示例场景是,购物车将在331号会议室拿走文件,并通过电梯和移动车送至442号会议室。

我想在一个python文件中声明3个客户端,但是Paho MQTT on_connect, on_message,...的内置函数仅适用于“一个”客户端。因此,在我的情况下,只有购物车客户端有效,并且控制台显示如下:

Cart connected with result code 0
cart/status b'ON'
cart/room/starting_room_number b'331'

您能帮助我如何使3个客户相互交流吗? 这是我的mqtt.py代码文件:

import paho.mqtt.client as mqtt 
import time

### Cart definition
def on_connect(client, obj, flags, rc):
    if rc == 0:
        print("Cart connected with result code " + str(rc))
    else:
        print("Bad connection returned code = ", rc)

def on_message(client, obj, msg):
    print(msg.topic + " " + str(msg.payload))

cart = mqtt.Client()
mobile = mqtt.Client()
elevator = mqtt.Client()

cart.on_connect = on_connect
cart.on_message = on_message

cart.connect("test.mosquitto.org", 1883, 60)
mobile.connect("test.mosquitto.org", 1883, 60)
elevator.connect("test.mosquitto.org", 1883, 60)

###(1)Call dolly
cart.subscribe("cart/status")
mobile.publish("cart/status", "ON")
time.sleep(1)

###(2)Get starting room number
cart.subscribe("cart/room/starting_room_number")
mobile.publish("cart/room/starting_room_number", "331")
time.sleep(1)

###(3)Call elevator
elevator.subscribe("elevator/status")
cart.publish("elevator/status", "ON")
time.sleep(1)

###(4)Enter floor
elevator.subscribe("elevator/starting_floor_number")
cart.publish("elevator/starting_floor_number", "3")
time.sleep(1)

###(5)Take document
mobile.subscribe("cart/document_status")
cart.publish("cart/document_status", "TAKEN")

###(6)Get destination room number
cart.subscribe("cart/room/destination_room_number")
mobile.publish("cart/room/destination_room_number", "442")

###(7)Call elevator
elevator.subscribe("elevator/status")
cart.publish("elevator/status", "ON")

###(8)Enter floor
elevator.subscribe("elevator/destination_floor_number")
cart.publish("elevator/destination_floor_number", "4")

###(9)Take document
mobile.subscribe("cart/document_status")
cart.publish("cart/document_status", "GIVEN")

cart.loop_forever()
# mobile.loop_forever()
# elevator.loop_forever()

1 个答案:

答案 0 :(得分:1)

您可以为每个客户端声明备用功能:

...
def on_connect_cart(client, obj, flags, rc):
    if rc == 0:
        print("Cart connected with result code " + str(rc))
    else:
        print("Bad connection returned code = ", rc)

def on_message_cart(client, obj, msg):
    print(msg.topic + " " + str(msg.payload))


def on_connect_mobile(client, obj, flags, rc):
    if rc == 0:
        print("Cart connected with result code " + str(rc))
    else:
        print("Bad connection returned code = ", rc)

def on_message_mobile(client, obj, msg):
    print(msg.topic + " " + str(msg.payload))
cart = mqtt.Client()
mobile = mqtt.Client()
elevator = mqtt.Client()

cart.on_connect = on_connect_cart
cart.on_message = on_message_cart
mobile.on_connect = on_connect_mobile
mobile.on_message = on_message_mobile
...