Skip to main content

Paho 的 MQTT 开发工具包

项目描述

Paho 的 MQTT 工具包

欢迎使用 Paho 的 MQTT 工具包。

为谁?为什么?

如果对于那些已经阅读了Paho 的 MQTT 库及其示例的文档并且像我一样觉得 API 在某种程度上偏离并且对于板载应用程序来说很复杂的人来说,这个工具包。

我个人喜欢 Paho 的 MQTT 库,无论如何我都不想替换它。但是,我想编写在某种程度上熟悉我使用的框架的应用程序,例如 Flask 或 Sanic。因此,通过使用具有简化 API 的可靠配置基础来抽象底层实现。

基本配置是什么?

该工具包的基本配置使用 Paho 的事件循环实现,方法是使用start_loopandstop_loop方法并创建一个接受不同配置参数的入口点方法,start_async.

简单用法

有关更多示例,请参阅示例目录。

import time

from paho.mqtt.client import Client

from pahotoolkit import (
    init,
    start_async,
    stop_async,
    subscribe,
    json_message,
)

from my_settings import (
    HOST,
    PORT,
    USERNAME,
    PASSWORD,
    LOG_CONFIG
)


@subscribe('/temperature')
def handle_temperature(mqtt_client: Client, userdata, message):
    print(f'Got {message}')


@subscribe('/my/topic')
@json_message()  # by default, non-json messages in the topic are ignored
def listen_my_topic(payload: dict, *args, **kwargs):
    # todo: do something with the payload
    pass


@on_connect()
def client_connected(mqtt_client: Client, *args, **kwargs):
    """Publish something on_connect."""
    mqtt_client.publish('/clients', 'Paho\'s MQTT toolkit message!')


# log_config => https://docs.python.org/3/library/logging.config.html#logging.config.dictConfig
# the default MQTT Client uses the default's MQTT Client constructor
# https://github.com/eclipse/paho.mqtt.python#client-1
def main():
    client: Client = start_async(host=HOST, port=PORT,  # port default to 1883 if not given
                                 username=USERNAME, password=PASSWORD,  # optional fields
                                 initialize=False, log_config=LOG_CONFIG)  # optional fields

    init(client)  # only required if initialize=False, else by default is automatically called

    while True:
        time.sleep(1)  # or do something in this thread...


if __name__ == '__main__':
    try:
        main()
    finally:
        stop_async()

接触

阿努尔福·索利斯

下载文件

下载适用于您平台的文件。如果您不确定要选择哪个,请了解有关安装包的更多信息。

源分布

pahotoolkit-0.1.4.2.tar.gz (6.3 kB 查看哈希)

已上传 source