首页 > 解决方案 > 使用 MQTT 传感器读数刷新 GUIZERO 文本。还没有正确更新

问题描述

因此,我正在开发一个 UI 项目,用于我自己的个人学习和充实。UI 需要能够使用 MQTT 发布的最新传感器读数来刷新其文本。我已经编写了一个简单的测试脚本来熟悉我将使用的工具,但是现在我的文本并没有随着即将到来的新读数而刷新。此外,我什至没有确定正在接收消息,当发布关于同一主题的消息时,控制台中不会显示任何内容。

这是我的代码:

from guizero import App, Text, TextBox, PushButton, Window, Box, Picture, Slider
import paho.mqtt.client as mqtt 

sensorReading = ''
#######################################
def on_connect(client, userdata):
    print("Connected with result code "+str(rc))
    
    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    client.subscribe("room/temperature")
#######################################


#######################################
def on_message(client, userdata, message):
    global sensorReading
    sensorReading = str(message.payload)  
    print("message received " ,str(message.payload.decode("utf-8")))
    print("message topic=",message.topic)
    print("message qos=",message.qos)
    print("message retain flag=",message.retain)
########################################

########################################
def updateReading():
    
    client.publish('room/temperature','84')
    reading.value = sensorReading
    reading.after(1000,updateReading)
    
########################################

brokerAddress = 'redacted'
client = mqtt.Client('GG1')

print("connecting to broker")
try:
    client.connect(brokerAddress, port=1883)
    print('Connection Successful!')
except:
    print('Connection Failed')
    exit(1)

client.on_message=on_message #attach function to callback

print("Subscribing to topic","room/temperature")

app = App(title='Admin Page Test', layout='auto', height=480,width=640)
app.bg = 'white'

client.loop_start()
welcomeText = Text(app, text='Welcome!', size=40, font='Times New Roman', color='darkgreen', align='top')
clientReading = Text(app,text='Latest Reading is: ')
reading=Text(app,text='****')
reading.after(1000, updateReading)

client.loop_stop()
app.display()

我知道这是我对这个系统背后的逻辑理解的错误,我只是不知道我错了哪一部分。感谢您的时间。

标签: python-3.xuser-interfacelogicmqtt

解决方案


推荐阅读