码迷,mamicode.com
首页 > 编程语言 > 详细

python 实现MQTT Client

时间:2019-05-18 09:23:07      阅读:876      评论:0      收藏:0      [点我收藏+]

标签:mes   queue   rom   message   return   class   one   usr   wait   

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

标签:mes   queue   rom   message   return   class   one   usr   wait   

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

(1)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!