1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- import paho.mqtt.client as mqtt
- import json
- import config_info_model as md
- from config_info_model import configInfoModel
- class mqttClient(object):
- confModel = None
- def __init__(self, confModel):
- self.confModel = confModel
- self.init_mqtt()
-
- # The callback for when the client receives a CONNACK response from the server.
- def on_connect(self, client, userdata, flags, rc):
- print("Connected with result code "+str(rc)) #rc的值很重要,为0代表连接成功。
-
- # Subscribing in on_connect() means that if we lose the connection and
- # reconnect then subscriptions will be renewed.
- self.client.subscribe("$SYS/#") #订阅$SYS/下的所有主题
- def init_mqtt(self):
- self.client = mqtt.Client(self.confModel.ip)
- self.client.username_pw_set(self.confModel.username, password=self.confModel.password)
- self.client.on_connect = self.on_connect #连接broker时broker响应的回调
- self.client.on_message = self.on_message #接收到订阅消息时的回调
-
- def subscribe_update_topic(self):
- self.client.connect(self.confModel.ip, 1883, 600) #连接到broker
- self.client.subscribe("1/1/9", 0)
- self.client.loop_forever()
-
- # 回调数据
- def on_message(self, client, userdata, msg):
- data = msg.payload
- jsonStr = data.decode('utf-8')
- data = json.loads(jsonStr)['values']
- data_dict = {}
- for i in range(len(data)):
- v = data[i]
- data_dict[v['code']] = v['v']
- print(data_dict)
-
- def data_to_array(jsonStr):
- data = json.loads(jsonStr)
- print(type(data))
- if __name__ == "__main__":
-
- cf = md.configInfoModel('jinfeng')
-
- ct = mqttClient(cf)
- ct.subscribe_update_topic()
- # ew = mqttClient()
- # ew.subscribe_update_topic()
|