2018年7月1日 星期日

mqtt@RaspberryPi

broker / server / client library install...
# 安裝 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


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") 

def on_message(client, userdata, msg):
  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()

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)




沒有留言:

VirtualBox 空間減肥

sdelete64 -z c: VBoxManage  modifymedium  disk  "/Users/fellow/VirtualBox VMs/Win10/Win10.vdi"  --compact *.vdi 路徑可以在 VirtualBox 儲...