首页 > 解决方案 > Raspberry Pi 作为 MQTT 代理以及订阅者或发布者

问题描述

场景:我有一个带有一些连接设备的本地网络,所以我想将命令从 android 应用程序发送到 Raspberry Pi,它将通过 MQTT 协议控制这些连接的设备,所以我可以使用 Raspberry Pi 作为代理以及客户端(发布者/订阅者) .

标签: androidpythonserverraspberry-pimqtt

解决方案


是的。您可以在同一个 Raspberry Pi 上运行代理和客户端。

import time
import paho.mqtt.client as paho
#broker="broker.hivemq.com"
broker="iot.eclipse.org"
#define callback
def on_message(client, userdata, message):
    time.sleep(1)
    print("received message =",str(message.payload.decode("utf-8")))

client= paho.Client("client-001") #create client object
#client1.on_publish = on_publish #assign function to callback
#client1.connect(broker,port) #establish connection
#client1.publish("house/bulb1","on")
######Bind function to callback
client.on_message=on_message
#####
print("connecting to broker ",broker)
client.connect(broker)#connect
client.loop_start() #start loop to process received messages
print("subscribing ")
client.subscribe("house/bulb1")#subscribe
time.sleep(2)
print("publishing ")
client.publish("house/bulb1","on")#publish
time.sleep(4)
client.disconnect() #disconnect
client.loop_stop() #stop loop

http://www.steves-internet-guide.com/into-mqtt-python-client/
http://www.steves-internet-guide.com/python-mqtt-publish-subscribe/

以上链接可以指导您解决问题。


推荐阅读