python 实现MQTT Client

Posted mftang2018

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 实现MQTT Client相关的知识,希望对你有一定的参考价值。

应用Python 实现MQTT Client,主要代码如下:

#coding:utf-8
#!/usr/bin/python3
import json
import os
import binascii
import asn1tools
import sys
import paho.mqtt.client as mqtt
import requests
import logging
from enum import Enum
from queue import Queue

__all__ = ["MQTTClient"]

class MQTTClient:

    def __init__(self,host, port, qos, timeout, log):
        self.host = host
        self.port = port
        self.qos = qos
        self.queue = Queue()
        self.mqtt_client = None
        self.timeout = timeout
        self.log = log

    def on_message(self, client, userdata, msg):
        self.log.debug(‘get a message: %s‘ % msg)
        self.queue.put(msg)

    def subscribe(self, topic):
        self.mqtt_client.subscribe(topic, self.qos)
        self.log.debug(‘subscribe to %s‘ % topic)

    def unsubscribe(self, topic):
        self.mqtt_client.unsubscribe(topic)
        self.log.debug(‘unsubscribe %s‘ % topic)

    def receive_msg(self, timeout=None):
        self.log.debug(‘waiting for message.‘)
        if timeout is None:
            timeout = self.timeout
        return self.queue.get(timeout=timeout)

    def publish(self, topic, blob):
        self.mqtt_client.publish(topic, blob)

    def loop_start(self):
        if self.mqtt_client is None:
            self.mqtt_client = mqtt.Client()
            self.mqtt_client.on_message = self.on_message
            self.mqtt_client.connect(self.host, self.port, self.timeout)
            self.mqtt_client.loop_start()

    def loop_stop(self):
        if self.mqtt_client is not None:
            self.mqtt_client.loop_stop()
            self.mqtt_client.disconnect()
            self.mqtt_client = None

  

以上是关于python 实现MQTT Client的主要内容,如果未能解决你的问题,请参考以下文章

python mqtt client publish操作

精简mqtt-client(python)

mqtt client python example

Python MQTT 实验

MQTT 客户端自动重连机制

5-Openwrt MQTT client使用