【发布时间】:2017-01-18 07:43:20
【问题描述】:
我正在为与 MQTT 集成的项目运行交通灯 (pi-stop) 解决方案。因此,发布者将计数发送给订阅者,订阅者将控制和更改交通信号灯。但是,我无法将任何计数发送给出版商。请指教,谢谢
MQTT_pub.py(发布者)
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
sub_topic = "light" #recieve message on this topic
pub_topic = "light" #send message to this topic
Broker = "127.0.1.1"
# when connecting to mqtt do this;
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe(sub_topic)
# when receiving a mqtt message do this;
def on_message(client, userdata, msg):
message = str(msg.payload)
print(msg.topic+" "+message)
# publish_mqtt("got your message")
# to send a message
def publish_mqtt(count):
mqttc = mqtt.Client("counting")
mqttc.connect(Broker, 1883)
mqttc.publish(pub_topic, "10")
#mqttc.loop(5) //timeout = 5s
def on_publish(mosq, obj, mid):
print("mid: " + str(mid))
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(Broker, 1883, 60)
publish_mqtt(0)
MQTT.py(订阅者)
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
import TrafficKit03
sub_topic = "light" #recieve message on this topic
pub_topic = "light" #send message to this topic
Broker = "127.0.0.1"
# when connecting to mqtt do this;
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe(sub_topic)
# when receiving a mqtt message do this;
def on_message(client, userdata, msg):
message = str(msg.payload)
print(msg.topic+" "+message)
# decide on traffic counting (if 5 display.. if 0 display..)
publish_mqtt(count)
TrafficKit03.call("TrafficKit03.py")
def on_subscribe(client, userdata, mid, gqos):
print("subscribed: " + gpos)
pass
def publish_mqtt(count):
mqttc = mqtt.Client("counting")
mqttc.connect(Broker, 1883)
mqttc.publish(pub_topic, "10")
#mqttc.loop(5) //timeout = 5s
client = mqtt.Client()
client.on_connect = on_connect
client.on_subscribe = on_subscribe
client.on_message = on_message
client.connect(Broker, 1883, 60)
client.loop_start()
【问题讨论】:
-
我之前没有使用过 Python 的 MQTT,但是你应该在
publisher.py中创建两个mqtt.Client()的实例吗? -
@Tagc 抱歉,我不太确定。