2018年11月7日12:22:13
環境:
Ubuntu 18.04
Python 3.6
1、安裝第三方庫
pip install paho-mqtt
2、代碼如下
參考資料: https://www.cnblogs.com/nulige/p/8993719.html
server_study.py
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
import time
idx = 0 # 往paho/temperature 一直發送內容
while True:
print("send success")
publish.single("paho/temperature",
payload="this is message:%s" % idx,
hostname="localhost",
client_id="lora1",
# qos = 0,
# tls=tls,
port=1883,
protocol=mqtt.MQTTv311)
idx = 1
time.sleep(5)
client_study.py
import paho.mqtt.client as mqtt
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print("Connected with result code " , str(rc))
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
# 在這裏處理業務邏輯
print(msg.topic ," " ,str(msg.payload))
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("localhost", 1883, 60) # 訂閱頻道
client.subscribe("paho/temperature")
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()
運行:
終端一:
python server_study.py
終端二:
python client_study.py
注: 運行會報錯因為沒有安裝mosquitto服務器
3、安裝mosquitto
參考資料 :https://blog.csdn.net/swedenfeng/article/details/53510048
sudo apt-get install mosquitto
sudo apt-get install libmosquitto-dev
sudo apt-get install mosquitto-clients
sudo service mosquitto status
測試是否安裝成功
# 終端一運行 接受信息
mosquitto_sub -h localhost -t "mqtt"-v
# 終端二運行 發布信息
mosquitto_pub -h localhost -t "mqtt"-m "Hello MQTT"
安裝成功後再運行第二步程序即可成功
4、 mosquitto可視化程序
安裝地址:http://www.jensd.de/apps/mqttfx/1.5.0/
參考資料:https://blog.csdn.net/nicholaszao/article/details/79211965