在我的树莓派上安装 paho mqtt 客户端并将我的 android 应用程序和 arduino 与我的代理连接后。我希望在收到来自应用程序或 arduino 客户端的消息后将此消息重新发布到此客户端,例如,如果我在收到“OFF”后收到“ON”,下一次发布将是“ON”“OFF”“ON”“OFF” “......或者我需要只是“开”或“关”
import paho.mqtt.client as mqtt
message = 'ON'
def on_connect(mosq, obj, rc):
print("rc: " + str(rc))
def on_message(mosq, obj, msg):
global message
print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload))
message = msg.payload
def on_publish(mosq, obj, mid):
print("mid: " + str(mid))
def on_subscribe(mosq, obj, mid, granted_qos):
print("Subscribed: " + str(mid) + " " + str(granted_qos))
def on_log(mosq, obj, level, string):
print(string)
mqttc = mqtt.Client()
# Assign event callbacks
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_publish = on_publish
mqttc.on_subscribe = on_subscribe
# Connect
mqttc.connect("localhost", 1883,60)
# Start subscribe, with QoS level 0
mqttc.subscribe("f", 0)
# Publish a message
#mqttc.publish("hello/world", "my message")
# Continue the network loop, exit when an error occurs
rc = 0
while rc == 0:
rc = mqttc.loop()
mqttc.publish("f",message)
print("rc: " + str(rc))