首页 > 编程语言 > 详细

python 实现MQTT Client

时间:2019-05-18 10:08:39      阅读:614      评论:0      收藏:0      [点我收藏+]

应用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

原文:https://www.cnblogs.com/mftang2018/p/10884565.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!