我对Python和MQTT都是新手。我能够编写一些Python工作代码来将连接的传感器数据发布到代理,现在我想订阅多个主题,并在连接到覆盆子的LCD 20x4上编写所有有效负载。
实际上,我编写了一个Python来订阅一个主题,并在LCD上编写有效负载;没有问题,它正在工作。无法在同一Python中包含其他主题并在LCD上编写有效负载。
跟随我的Python代码,你可以找到“只”一个主题的Python代码。
#!/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()
发布于 2017-01-18 16:38:12
我可以使用paho python mqtt库订阅多个主题。我已经创建了一个主题列表,并将其传递给"subscribe.simple“。使用下面的示例程序,我可以订阅"topic1“和"topic2”。
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
https://stackoverflow.com/questions/41624697
复制相似问题