为什么我的 Python MQTT 发布者没有发布任何东西

Why isnt my Python MQTT publisher publish anything out

我是 运行 我的项目与 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()

正如@Tagic 所说,您需要删除额外的 mqtt.Client() 个实例

编辑这两个文件以删除 publish_mqtt 函数中的额外连接

def publish_mqtt(count):
    #mqttc = mqtt.Client("counting")
    #mqttc.connect(Broker, 1883)
    mqttc.publish(pub_topic, "10")
    #mqttc.loop(5) //timeout = 5s

在 MQTT_pub.py 文件中,您还应该将对 publish_mqtt 的调用移动到 on_connect 函数:

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    publish_mqtt(0)

并开始网络循环

client.connect(Broker, 1883, 60)
client.loop_start()