zoukankan      html  css  js  c++  java
  • 应用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
  • 相关阅读:
    2017-2018-2 20165207 实验四《Android开发基础》实验报告
    2017-2018-2 20165207 实验三《敏捷开发与XP实践》实验报告
    20165207 第九周学习总结
    20165328 实验四《Andriid应用开发》实验报告
    20165328 第十二周课上补做
    20165328 课下作业补做
    20165328 第九周学习总结
    2017-2018-2 20165328 实验三《敏捷开发与XP实践》实验报告
    20165328 结对编程第二周整体总结
    20165328课上补做
  • 原文地址:https://www.cnblogs.com/shengs/p/12131817.html
Copyright © 2011-2022 走看看