代码拉取完成,页面将自动刷新
# -*- coding: utf-8 -*-
import logging
import paho.mqtt.client as mqtt
from functools import partial
import json
class MQTTTunnel:
def __init__(self):
self.mqtt_client = mqtt.Client()
self.globalStatus = None
self.topic_to_subscribe = None
def on_connect(self,client, userdata, flags, rc):
if rc == 0:
self.globalStatus.isMQTTConnected = True
self.globalStatus.RunStatus = True
# logging.debug("Connected with result code " + str(rc))
# if self.topic_to_subscribe:
# client.subscribe(self.topic_to_subscribe)
else:
logging.error("Failed to connect, return code " + str(rc))
def on_message(client, userdata, msg):
payload_str =msg.payload.decode('utf-8')
logging.debug(msg.topic+" "+payload_str)
def publish(self,topic,tag, data):
logging.info(tag+":"+str(data))
if len(data) == 4:
dict_list = {"Tag": tag, "Value": data[1], "Time": data[3]}
elif len(data) == 3:
dict_list = {"Tag": tag, "Value": data[0], "Time": data[2]}
json_data = json.dumps(dict_list, indent=3)
result = self.mqtt_client.publish(topic, json_data)
if result.rc != 0:
logging.error("Failed to publish data to MQTT Broker.")
def connect(self,config,globalStatus):
self.globalStatus = globalStatus
self.topic_to_subscribe = config["mqtttopic"]
self.mqtt_client.username_pw_set(config["mqttuser"], config["mqttpassword"])
self.mqtt_client.on_connect = self.on_connect
self.mqtt_client.connect(config["mqttserver"], 1883, 60)
self.mqtt_client.loop_start()
def disconnect(self,globalStatus):
globalStatus.isMQTTConnected = False
globalStatus.RunStatus= False
self.mqtt_client.loop_stop()
self.mqtt_client.disconnect()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。