python mqtt通訊(windows)

 

 

一、消息隊列伺服器

這裡我用到activemq,可到官網下載 //activemq.apache.org/

1. 若遇到點擊apache-activemq-5.16.2\bin\activemq.bat 出現閃退,64位系統請點擊apache-activemq-5.16.2\bin\win64\activemq.bat,啟動mqtt伺服器
ActiveMQ啟動閃退的問題可見 //blog.csdn.net/pavel101/article/details/79460672
2. ActiveMQ 默認用戶名和密碼
用戶名:admin 密碼:admin
可以在/conf/users.properties中尋找。
默認登錄地址://localhost:8161/admin/,這裡mqtt默認埠為1883,ip為192.168.1.103

二、封裝客戶端

 1 import paho.mqtt.client as mqtt
 2 
 3 import logging
 4 
 5 class MqttClient(mqtt.Client):
 6 
 7     def initClient(self, mqttServer, mqttPort, username, password, timeout=10000):
 8         logging.basicConfig(level=logging.DEBUG)
 9 
10         self.mqttServer = mqttServer
11         self.mqttPort = mqttPort
12         self.username_pw_set(username, password=password)
13 
14         self.connect(self.mqttServer, self.mqttPort, timeout)  # keeplive僅為10000秒
15         self.on_connect = self.on_connect
16 
17     def getClient(self):
18         return self.client
19 
20     def on_connect(self, client, userdata, flags, rc):
21         linkAddr = client.mqttServer + ":"+ str(client.mqttPort)
22         if rc == 0:
23             logging.info("與mqtt伺服器:"+ linkAddr +"連接成功")
24         elif rc == 1:
25             logging.error("協議版本錯誤")
26         elif rc == 2:
27             logging.error("無效的客戶端標識")
28         elif rc == 3:
29             logging.error("服務端無法使用")
30         elif rc == 4:
31             logging.error("與mqtt伺服器連接失敗: 錯誤的用戶名或密碼 ")
32         elif rc == 5:
33             logging.error("登錄用戶未經授權 ")
34         else:
35             logging.error("與mqtt伺服器:%s 連接返回異常結果:%s " % (linkAddr, str(rc)))
36 
37     def on_subscribe(self, client, userdata, mid, granted_qos):
38         logging.info("訂閱成功: " + str(mid) + " " + str(granted_qos))
39 
40     def on_publish(self, client, userdata, mid):
41         logging.info("OnPublish, mid: " + str(mid))

 

三、下面模擬客戶端1和客戶端2通訊,客戶端1發布資訊,客戶端2接收資訊

客戶端1程式碼

 1 #!/usr/bin/python
 2 import datetime
 3 import json
 4 import logging
 5 import time
 6 
 7 from mqttService.mqttClient import MqttClient
 8 
 9 #------------------客戶端1--------------------
10 # ======================================================
11 
12 
13 # 伺服器地址
14 mqttServer = "192.168.1.103"
15 # 通訊埠
16 mqttPort = 1883
17 # 訂閱主題
18 devTopic = '/devices/dev1'
19 responseDevTopic= '/7.0/dev1'
20 
21 
22 # 接收客戶端2響應資訊
23 def on_message(client, userdata, message):
24     curtime = datetime.datetime.now()
25     strcurtime = curtime.strftime("%Y-%m-%d %H:%M:%S")
26     logging.info("%s: 接收 %s 響應資訊:主題:%s 內容:%s" %(strcurtime, mqttServer+":"+str(mqttPort), message.topic, str(message.payload, encoding = "utf-8")))
27 
28 
29 if __name__ == '__main__':
30     logging.basicConfig(level=logging.DEBUG)
31 
32     username = "UserName1"
33     password = "PassWord1"
34 
35     client = MqttClient()
36     client.initClient(mqttServer, mqttPort, username, password)
37     client.subscribe(responseDevTopic, qos=0)  #訂閱主題
38     client.on_message = on_message
39 
40     msg = 'hello world'
41     for i in range(1000):
42         client.publish(devTopic, payload=msg , qos=0)  #發布資訊
43         time.sleep(4)
    client.loop_forever()  # 持續連接

 

客戶端2程式碼

 #!/usr/bin/python
 import datetime
 import json
 import logging
 
 from mqttService.mqttClient import MqttClient
 
  #------------------客戶端2-------------------
  
 # 訂閱主題
 devTopic = '/devices/#'
# 發布主題
responseDevTopicPrefix = '/7.0/' def on_message(client, userdata, message): curtime = datetime.datetime.now() strcurtime = curtime.strftime("%Y-%m-%d %H:%M:%S") recvMsg = message.payload # 獲取發送設備的設備ID topicArr = str(message.topic).split("/") topicArr = [item for item in filter(lambda x: x != '', topicArr)] # 去除空串 deviceId = topicArr[1] logging.info("%s: 接收硬體裝置 %s 資訊:主題: %s 內容: %s" %(strcurtime, deviceId, message.topic, recvMsg)) # 發送響應回硬體終端 client.publish(responseDevTopicPrefix +deviceId, payload="收到數據"+recvMsg, qos=0)if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) mqttAddr = '192.168.1.103' mqttPort = 1883 username = "UserName2" password = "PassWord2" # 與客戶端1通訊 client = MqttClient() client.initClient(mqttAddr, mqttPort, username, password) client.subscribe(devTopic, qos=0) client.on_message = on_message client.loop_start() # 開始監聽 # 阻塞主程式 while True: pass

 

Tags: