首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >MQTT/Python订阅多个主题并在Raspberry LCD上编写有效负载

MQTT/Python订阅多个主题并在Raspberry LCD上编写有效负载
EN

Stack Overflow用户
提问于 2017-01-13 07:09:27
回答 1查看 15.7K关注 0票数 4

我对Python和MQTT都是新手。我能够编写一些Python工作代码来将连接的传感器数据发布到代理,现在我想订阅多个主题,并在连接到覆盆子的LCD 20x4上编写所有有效负载。

实际上,我编写了一个Python来订阅一个主题,并在LCD上编写有效负载;没有问题,它正在工作。无法在同一Python中包含其他主题并在LCD上编写有效负载。

跟随我的Python代码,你可以找到“只”一个主题的Python代码。

代码语言:javascript
复制
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# RPi-S-LCD.py
# Created on 8/1/2017
#
# Python program that write payloads on LCD 20x4
#

import time
import sys
import os
import paho.mqtt.client as paho
sys.path.append("/home/pi/Adafruit_Python_CharLCD")
import Adafruit_CharLCD as LCD
import Adafruit_GPIO.MCP230xx as MCP

### Define MCP pins connected to LCD
lcd_rs = 6
lcd_en = 4
lcd_d4 = 3
lcd_d5 = 2
lcd_d6 = 1
lcd_d7 = 0
lcd_backlight = None

### Define LCD type
lcd_columns = 20
lcd_rows = 4

### Initialize MCP23017 for LCD
gpiomcp = MCP.MCP23017(0x20, busnum=1)

### Initialize LCD panel parameters
lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7, lcd_columns, lcd_rows, lcd_backlight, gpio=gpiomcp)
lcd.show_cursor(False)
lcd.blink(False)
lcd.clear()

### Read data from MQTT broker
def on_subscribe(client, userdata, mid, granted_qos):
    print("Subscribed to the broker "+str(mid)+" "+str(granted_qos))


### Print topic data to LCD
def on_message1(client, userdata, msg):
    lcd.set_cursor(0,0)
    lcd.message(msg.payload)

client = paho.Client()
client.on_subscribe = on_subscribe
client.on_message = on_message1
client.connect("10.0.2.10", 1883, 30)
client.subscribe("iDomus/Time",2)

client.loop_forever()
EN

回答 1

Stack Overflow用户

发布于 2017-01-18 16:38:12

我可以使用paho python mqtt库订阅多个主题。我已经创建了一个主题列表,并将其传递给"subscribe.simple“。使用下面的示例程序,我可以订阅"topic1“和"topic2”。

代码语言:javascript
复制
topic = ["topic1", "topic2"]
hostname_1 = "<mqtt broker host name>"
port_1 = <mqtt broker connection port>
username_1 = "broker username"
password_1 = "broker password"
message = subscribe.simple(topic, hostname=hostname_1, port=port_1, keepalive=60, will=None, auth={'username':username_1,'password':password_1})
print meaasge.payload
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41624697

复制
相关文章

相似问题

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