简体   繁体   English

MQTT订阅者与MQTT发布者订阅同一主题失败

[英]MQTT Subscriber Failed to Subscribe to the Same Topic With MQTT Publisher

I'm trying to make a simple "transit schedule changes" program using python MQTT where the publisher can input flight number (will be used as topic) and new flight time, while the transit location will be picked random from given list.我正在尝试使用 python MQTT 制作一个简单的“中转时间表更改”程序,发布者可以在其中输入航班号(将用作主题)和新的航班时间,而中转位置将从给定列表中随机选择。

The subscriber will have to input flight number too which will be used as topic.订户还必须输入将用作主题的航班号。 But in my codes, it looks like the subscriber failed to get the message published to the same topic because it keeps on printing Connected Successfully (I'm using client.loop_forever() ).但是在我的代码中,订阅者似乎无法将消息发布到同一主题,因为它一直在打印Connected Successfully (我正在使用client.loop_forever() )。 Can someone please help me to figure out what's wrong with my code?有人可以帮我弄清楚我的代码有什么问题吗?

This is my first time asking question, so please ask me if something isn't clear from my explanation.这是我第一次提问,所以如果我的解释中有什么不清楚的地方请问我。 Thank you so much:)太感谢了:)

Publisher:出版商:

import paho.mqtt.client as mqtt
import time
from datetime import datetime, date
import random

def on_connect(client, userdata, flags, rc):
    if (rc==0):
        global connected
        connected = True
        #print("Successfully Connected.")
        client.on_publish = on_publish
    else:
        print("Failed to connect.")
        
def on_publish(client, userdata, mid):
    print("Published successfully. MID: "+str(mid))
    

listTransit = ["Singapura", "Qatar", "Korea Selatan", "Turki", "Republik Tiongkok",
                "Amerika Serikat", "Jepang", "Uni Emirat Arab", "Oman", "Islandia"]
                
broker_address="broker.emqx.io"

client = mqtt.Client("Publisher")
client.on_connect = on_connect
client.connect(broker_address, port=1883)

client.loop_start()

topic = input("Masukkan nomor penerbangan: ")
negaraTujuan = input("negara tujuan: ")
print("Masukkan waktu penerbangan baru (Format: [jam::menit::detik])")
str_time = input()

Date = date.today()
Time = datetime.strptime(str_time, '%H::%M::%S').time()
Location = random.randrange(0,len(listTransit))

if (listTransit[Location] != negaraTujuan):
    message = Date.strftime("%Y/%m/%d")+"\nTujuan: "+negaraTujuan+"\nLokasi Transit  : "+listTransit[Location]+"\nJam terbang    : "+Time.strftime("%H:%M:%S")
    client.publish(topic, message)
    print("Topic: ",topic)
    print(message)
else:
    while listTransit[Location] == negaraTujuan:
        Location = random.randrange(0,len(listTransit))
    message = Date.strftime("%Y/%m/%d")+"\nTujuan: "+negaraTujuan+"\nLokasi Transit  : "+listTransit[Location]+"\nJam terbang    : "+Time.strftime("%H:%M:%S")
    client.publish(topic, message)
    print(message)
    
client.loop_stop()

Subscriber:订户:

import paho.mqtt.client as mqtt
import time
from datetime import datetime, datetime
import re

def on_connect(client, userdata, flags, rc):
    if (rc == 0):
        print("Connected successfully.")
        #global topic
        #topic = input("Masukkan nomor penerbangan anda: ")
        #client.subscribe(topic)
    else:
        print("Connection failed.")
        
def on_message(client, userdata, msg):
    print("on_message callback function activated.")
    sched = str(msg.payload.decode("utf-8"))
    print(sched)
    
def on_subscribe(client, userdata, mid, granted_qos):
    print("Subscribed to "+topic+" successfully")
    
    
broker_address="broker.emqx.io"
topic = input("Masukkan nomor penerbangan anda: ")
negaraTujuan = input("negara tujuan: ")

client = mqtt.Client("Subscriber")
client.subscribe(topic)
client.on_connect = on_connect
client.on_message = on_message
client.on_subscribe = on_subscribe
client.connect(broker_address, port=1883)

client.loop_forever()

what I got from running both codes are我从运行这两个代码得到的是

Masukkan nomor penerbangan: YT05TA
negara tujuan: Australia
Masukkan waktu penerbangan baru (Format: [jam::menit::detik])
12::50::00
Topic:  YT05TA
2023/01/03
Tujuan: Australia
Lokasi Transit  : Amerika Serikat
Jam terbang    : 12:50:00
Published successfully. MID: 1

from Publisher来自出版商

and

Masukkan nomor penerbangan anda: YT05TA
negara tujuan: Australia
Connected successfully.
Connected successfully.
Connected successfully.
Connected successfully.

from subscriber.来自订户。 It doesn't even print the print("on_message callback function activated.")它甚至不打印print("on_message callback function activated.")

You are using a public broker, so that means it is likely to have LOTS of over clients.您使用的是公共经纪人,这意味着它可能有很多超额客户。

Every client MUST have a UNIQUE Client ID, so using Publisher and Subscriber is very likely to clash with other clients.每个客户端都必须有一个唯一的客户端 ID,因此使用Publisher者和Subscriber很可能会与其他客户端发生冲突。

The MQTT specification says the broker must disconnect the currently connected client when a new client connects with the same Client ID. MQTT 规范规定,当新客户端使用相同的客户端 ID 连接时,代理必须断开当前连接的客户端。 As most client libraries will try and reconnect when they are disconnects this leads to a battle between the two clients to stay connected.由于大多数客户端库在断开连接时会尝试重新连接,这会导致两个客户端之间为保持连接而进行的战斗。

Change them both to random values将它们都更改为随机值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM