为什么我的Python MQTT发布者不会发布任何内容

时间:2017-01-18 07:43:20

标签: python mqtt publisher

我正在为与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()

1 个答案:

答案 0 :(得分:0)

正如@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()