我正在MQTT服务器(mosquitto)上发送从DHT22传感器获取的数据。我想知道的是在文本字段中显示我正在接收的数据(数据始终不断地发送到MQTT服务器),并在每次接收到数据时对其进行更新。
这是TKinter代码:
main=Tk()
main.title('sensor data')
main.geometry('700x500')
temp_label=ttk.Label(main,text='Temperature Readings')
temp_label.grid(column=0,row=0,sticky=(N,W))
temperature=DoubleVar()
temp_entrybox=ttk.Entry(main,textvariable=temperature,width=25)
temp_entrybox.grid(column=0,row=1,sticky=(N,W))
humid_label=ttk.Label(main,text='Humidity Readings')
humid_label.grid(column=1,row=0,sticky=(N,W))
humidity=DoubleVar()
humid_entrybox=ttk.Entry(main,textvariable=humidity,width=25)
humid_entrybox.grid(column=1,row=1,sticky=(N,W))
boutton=ttk.Button(main,text='connect',command=fon)
boutton.grid(column=0,row=2,sticky=(N,W))
没有什么太复杂的,只有2个文本字段和一个名为connect的按钮可以建立连接。问题出在以下代码中:
from tkinter import *
from tkinter import ttk
import paho.mqtt.client as mqtt
import time
temp = []
humid=[]
def on_message(client, userdata, message):
print("hi") # I did that to see if it is entering the on_message function and as expected it's not even entering it once.
global t
global h
m=str(message.payload.decode("utf-8"))
t=m[16:20]
h=m[34:38]
#connecting to the MQTT server on my own topic.
def on_connect(client, userdata, flags, rc):
client.subscribe("DHT22_cimti_project_pe")
# This code will get executed when the button is clicked
def fon():
client = mqtt.Client()
client.on_message = on_message
client.on_connect = on_connect
client.connect(broker)
temperature.set(float(t)) #This should display dynamically the temperature in the textfield named "temperature"
humidity.set(float(h)) #Same but for the humidity
client.loop_forever()
broker="test.mosquitto.org"
问题是出现以下错误:
Name t is not defined.
我在print("hi")
函数中做了一个on_message
,以查看它是否还在输入,并且按预期没有输入。