前言
經歷過各種問題的磨難終於基本搭建完成了自己的MQTT服務器,接下來我就趕緊寫個Python程序測試下.
安裝
這裏採用paho.mqtt.python編寫程序,詳情參閱這裏
打開powershell,執行pip install paho-mqtt
安裝模塊
程序
# coding=utf-8
import json
import threading
import paho.mqtt.client as mqtt
# 當連接上服務器後回調此函數
import time
from my_lib.code_handle.code_handle import auto_code
from windows_info.read_info import Win_psutil
class MqttClient:
client = mqtt.Client('tester')
def __init__(self, host, port):
self._host = host
self._port = port
self.client.on_connect = self._on_connect # 設置連接上服務器回調函數
self.client.on_message = self._on_message # 設置接收到服務器消息回調函數
def connect(self, username='tester', password='tester'):
self.client.username_pw_set(username, password)
self.client.connect(self._host, self._port, 60) # 連接服務器,端口爲1883,維持心跳爲60秒
def publish(self, topic, data):
self.client.publish(topic, data)
def loop(self, timeout=None):
thread = threading.Thread(target=self._loop, args=(timeout,))
# thread.setDaemon(True)
thread.start()
def _loop(self, timeout=None):
if not timeout:
self.client.loop_forever()
else:
self.client.loop(timeout)
def _on_connect(self, client, userdata, flags, rc):
print("\nConnected with result code " + str(rc))
client.subscribe("test-0")
def _on_message(self, client, userdata, msg): # 從服務器接受到消息後回調此函數
print "\n主題:" + auto_code(str(msg.topic)) + " 消息:" + auto_code(str(msg.payload))
def _is_json(self, data):
try:
json.loads(data)
except ValueError:
return False
return True
def publish_loop(self):
pass
if __name__ == '__main__':
host=None
client = MqttClient(host, 1883)
client.connect('tester','tester')
client.publish('test-0', '我上線啦!')
client.loop()
wp = Win_psutil()#自己定義的一個類
while True:
data_json=wp.auto_json()#方法返回一個包含CPU和進程信息的JSON字符串
client.publish('test-0',data_json)
time.sleep(2)
這裏自己封裝了類,主要功能是連上服務器訂閱默認主題,接收到消息即打印出來.
在主程序中先實例化類,接着使用默認用戶名與密碼登陸,在主題"test-0上"發佈信息,接着定時將打包成JSON信息的數據發佈到"test-0"這個主題