這篇文章主要講解了“基于python怎么安裝MQTT客戶端”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“基于python怎么安裝MQTT客戶端”吧!
MQTT是一個輕量級的消息協議。從2014年12月IOIT大會上得到的消息,該協議已經被OASIS標準組織接收,成立了專門的工作組,以意味著該規范正式走向了標準化之路。
一個輕量級的MQTT服務器是:http://www.mosquitto.org,可以運行ARM/MIPS的嵌入式linux系統上,如OpenWRT。
很多客戶端模塊現在被Eclipse基金會接管,發展很快。
下面介紹基于python的MQTT的客戶端的安裝:
git clone http://git.eclipse.org/gitroot/paho/org.eclipse.paho.mqtt.python.git cd org.eclipse.paho.mqtt.python sudo python setup.py install
注意,如果使用Sublime,最好到里面的控制臺進行安裝,缺省運行在獨立的環境中,跟系統的控制臺安裝的程序不一樣。
然后,發送消息:
#!/usr/bin/python
# This shows a service of an MQTT subscriber.
# Copyright (c) 2010-2015, By openthings@163.com.
import sys
import datetime
import socket, sys
import paho.mqtt.publish as publish
def transmitMQTT(strMsg):
#strMqttBroker = "localhost"
strBroker = "112.124.67.178"
strMqttChannel = "/inode/mychannel"
print(strMsg)
publish.single(strMqttChannel, strMsg, hostname = strMqttBroker)
if __name__ == '__main__':
transmitMQTT("Hello,MQTT Proxy, I am client inside python.")
print "Send msg ok."
創建一個MQTT服務器程序:
#!/usr/bin/python
# This shows a service of an MQTT subscriber.
# Copyright (c) 2010-2015, By openthings@163.com.
import sys
import datetime
import socket, sys
#======================================================
#MQTT Initialize.--------------------------------------
try:
import paho.mqtt.client as mqtt
except ImportError:
print("MQTT client not find. Please install as follow:")
print("git clone http://git.eclipse.org/gitroot/paho/org.eclipse.paho.mqtt.python.git")
print("cd org.eclipse.paho.mqtt.python")
print("sudo python setup.py install")
#======================================================
def on_connect(mqttc, obj, rc):
print("OnConnetc, rc: "+str(rc))
def on_publish(mqttc, obj, mid):
print("OnPublish, mid: "+str(mid))
def on_subscribe(mqttc, obj, mid, granted_qos):
print("Subscribed: "+str(mid)+" "+str(granted_qos))
def on_log(mqttc, obj, level, string):
print("Log:"+string)
def on_message(mqttc, obj, msg):
curtime = datetime.datetime.now()
strcurtime = curtime.strftime("%Y-%m-%d %H:%M:%S")
print(strcurtime + ": " + msg.topic+" "+str(msg.qos)+" "+str(msg.payload))
on_exec(str(msg.payload))
def on_exec(strcmd):
print "Exec:",strcmd
strExec = strcmd
#=====================================================
if __name__ == '__main__':
mqttc = mqtt.Client("mynodeserver")
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_publish = on_publish
mqttc.on_subscribe = on_subscribe
mqttc.on_log = on_log
#strBroker = "localhost"
strBroker = "112.124.67.178"
mqttc.connect(strBroker, 1883, 60)
mqttc.subscribe("/inode/mychannel", 0)
mqttc.loop_forever()感謝各位的閱讀,以上就是“基于python怎么安裝MQTT客戶端”的內容了,經過本文的學習后,相信大家對基于python怎么安裝MQTT客戶端這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。