标签: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
标签:mes queue rom message return class one usr wait
原文地址:https://www.cnblogs.com/mftang2018/p/10884565.html