# 安裝 broker 及 所需函式庫
sudo apt-get install mosquitto mosquitto-clients
sudo apt-get install python3-pip
sudo pip3 install paho-mqtt
fix python search path...
# poah 安裝路徑若 python 找不到要作修正
cd /usr/lib/python2.7/dist-packages
sudo ln -s /usr/local/lib/python3.5/dist-packages/paho
import paho.mqtt.client as mqtt
sudo ln -s /usr/local/lib/python3.5/dist-packages/paho
subscribe...
# Subscribe 訂閱訊息/接收訊息
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe("where/is/my/topic")
print("Connected with result code "+str(rc))
client.subscribe("where/is/my/topic")
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
print(msg.topic+" "+str(msg.payload))
client = mqtt.Client()
client.on_connect = on_connect #call back function
client.on_message = on_message #call back function
client.connect("localhost", 1883, 60)
client.loop_forever()
client.on_connect = on_connect #call back function
client.on_message = on_message #call back function
client.connect("localhost", 1883, 60)
client.loop_forever()
pubilsh...
# Publisher 發佈訊息
import paho.mqtt.publish as publish
# publish a message then disconnect.
host = "localhost"
topic = "where/is/my/topic"
payload = "hello"
# If broker asks user/password.
auth = {'username': "", 'password': ""}
# If broker asks client ID.
client_id = ""
publish.single(topic, payload, qos=1, hostname=host)
#publish.single(topic, payload, qos=1, host=host, auth=auth, client_id=client_id)
沒有留言:
張貼留言