首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Mqtt订阅和阅读多个主题

Mqtt订阅和阅读多个主题
EN

Stack Overflow用户
提问于 2018-08-12 16:22:54
回答 1查看 2.4K关注 0票数 1

我需要读取两个传感器,并在pygame窗口上获得结果。我有一个pi zero作为传感器的发布者和代理运行。它创建了两个主题,“房子”和“热”。在第二个pi (virtualbox上的jessie)上,我运行以下python脚本,并获得预期的结果。因此,我会问,为了从两个不同的主题获得两个值,我选择创建两个不同的客户端(具有两个不同的on_message)是否是正确的选择。请原谅我在代码中的错误或不准确,我不是专家,我一个月前才认识Mosquitto。这些代码中的大部分都是仅用于测试mqtt的原始代码。在网上冲浪时,我没有找到关于如何读取传感器数值并将其放入窗口(如pygame或Tkinter)的实用示例,而无需使用云应用程序和python和pi;有人知道这样的教程吗?谢谢

代码语言:javascript
运行
复制
import time
import paho.mqtt.client as paho
import pygame, sys

pygame.init()
screen = pygame.display.set_mode((640,480),0,32)
background = pygame.Surface(screen.get_size())
background.fill((0,0,0))
font = pygame.font.SysFont("comicsansms", 72)

broker = "192.168.100.21"

ss=''
tt=''
def omessage(client, userdata, message):
    if message.topic=="house":
        global ss
        ss=(str(message.payload.decode("utf-8")+message.topic))
    if message.topic=="heat":
        global tt
        tt=(str(message.payload.decode("utf-8")+message.topic))

client=paho.Client("cliente-001")
client.on_message=omessage
client.connect(broker)
client.loop_start()

client.subscribe("house")
client.subscribe("heat")
while True:
    screen.blit(background, (0,0))

    text=font.render(" %s" %ss, True, (0,255,0))
    textRect = text.get_rect()
    screen.blit(text,textRect)

    text1=font.render(" %s" %tt, True, (0,255,0))
    text1Rect = text1.get_rect(center=(150,150))
    screen.blit(text1,text1Rect)
    time.sleep(0.2)    
    pygame.display.update()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
pygame.quit()
sys.exit()
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51807052

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档