mqtt 的值未发送

问题描述 投票:0回答:1

我在proteus中运行一个智能停车并在kivy中构建一个应用程序。所以问题是当我运行代码时它只显示unknown.img,例如slot1未知,slot2未知,slot3未知

我如何建立连接。 没有猕猴桃,连接很好,它显示了结果

import paho.mqtt.client as mqtt
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.image import Image
from kivy.uix.label import Label

broker_address = "broker.hivemq.com"  # Replace with your MQTT broker address
slot1_topic = "slot1"
slot2_topic = "slot2"
slot3_topic = "slot3"


slot_statuses = {
    slot1_topic: "Unknown",
    slot2_topic: "Unknown",
    slot3_topic: "Unknown"
}

slot_labels = {}
slot_images = {}

def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))
    if rc == 0:
        print("Connected to MQTT broker")
    else:
        print("Connection failed. Return code: " + str(rc))

    # Subscribe to parking slot topics
    client.subscribe(slot1_topic)
    client.subscribe(slot2_topic)
    client.subscribe(slot3_topic)


def on_message(client, userdata, msg):
    topic = msg.topic
    status = msg.payload.decode()
    slot_statuses[topic] = status
    update_gui()



def update_gui():
    for slot, status in slot_statuses.items():
        label = slot_labels[slot]
        image = slot_images[slot]
        if status == "1":
            label.text = f"{slot} Parked"
            image.source = f"{slot}car_parked.png"
        elif status == "0":
            label.text = f"{slot} Free"
            image.source = f"{slot}car_free.png"
        else:
            label.text = f"{slot} Unknown"
            image.source = "unknown.jpg"

client = mqtt.Client()


client.on_connect = on_connect
client.on_message = on_message

client.connect(broker_address, 1883, 60)


class ParkingApp(App):
    def build(self):
        layout = BoxLayout(orientation='vertical')
        for slot in slot_statuses:
            label = Label(text=f"{slot} Unknown", halign='center', valign='middle')
            image = Image(source="unknown.jpg")  # Default image for unknown state
            layout.add_widget(label)
            layout.add_widget(image)
            slot_labels[slot] = label
            slot_images[slot] = image
        return layout


if __name__ == '__main__':
    app = ParkingApp()
    app.run()

mqtt (0,1) 中的值应该传递给上面的代码

python kivy mqtt iot
1个回答
0
投票

我对mqtt不熟悉,但是快速浏览一下文档,mqtt中的“动作”发生在网络循环中。 Kivy 也是基于循环的。您需要整合两个循环。

查看:https://eclipse.dev/paho/index.php?page=clients/python/docs/index.php#network-loop

我建议使用 kivy 时钟来安排对循环()的调用,以您的应用程序可以支持的最长定期间隔。我还将循环中的超时设置得很短(0.25 或更短)。超时时间太长会导致 gui 在等待超时时锁定。

© www.soinside.com 2019 - 2024. All rights reserved.