python3异步MQTT库HBMQTT(2) - broker代理API使用说明

HBMQTT

本文介绍在python程序中如何接入异步 mqtt broker,异步客户端API和命令行用法请参考前面两篇文章。

简介

开源的Mqtt客户端和broker,使用python标准异步库asyncio实现,提供协程并发程序开发的直接API。

  • GitHub:https://github.com/beerfactory/hbmqtt
  • 文档:https://hbmqtt.readthedocs.io/en/latest/

Feature

HBMQTT实现了完整的MQTT 3.1.1协议规范,并提供了以下特性:

  • Support QoS 0, QoS 1 and QoS 2 messages flow
  • 客户端断线自动重连
  • 通过密钥文件认证(其他方法可通过插件系统实现)
  • 基础的$SYS topics 支持
  • TCP 和 websocket 支持
  • TCP 和 websocket 的 SSL 支持
  • 插件系统

依赖

要求Python >=3.4.3

安装

pip install hbmqtt==0.9.6

Broker API参考

hbmqtt.broker.Broker基于了MQTT 3.1.1 协议标准,实现了broker代理服务器的基本功能,

1. 用法示例

config 参数配置请参考前面文章 - 命令行基本用法 ,或者参考官方示例

import asyncio
import logging

from hbmqtt.broker import Broker

logger = logging.getLogger(__name__)

config = {
    'listeners': {
        'default': {
            'type': 'tcp',
            'bind': '0.0.0.0:1883',
            'max_connections': 10,
        },
    },
    'sys_interval': 10,
    'auth': {
        'allow-anonymous': True,
    },
    'topic-check': {
        'enabled': False
    }
}

broker = Broker(config)


async def test_coro():
    # 启动
    await broker.start()
    await asyncio.sleep(5)
    # 终止
    await broker.shutdown()


if __name__ == '__main__':
    formatter = "[%(asctime)s] :: %(levelname)s :: %(name)s :: %(message)s"
    logging.basicConfig(level=logging.INFO, format=formatter)
    asyncio.get_event_loop().run_until_complete(test_coro())

    # asyncio.get_event_loop().run_forever() # 让 broker 一直执行

2. API 参考

1. Broker构造方法 [source]

class hbmqtt.broker.Broker(config=None, loop=None, plugin_namespace=None)

参数:

  • config: python字典类型,字段参考下文配置
  • loopasyncio模块中的loop()对象
  • plugin_namespace:加载插件入口点时使用的插件命名空间,默认使用hbmqtt.broker.plugins

2. broker.start

协程,启动broker

broker.start()

3. broker.shutdown

协程, 关闭broker

broker.shutdown()

4. python读取yaml

读取从yaml文件,转为python对象

import yaml

with open('broker.yaml') as f:
    print(yaml.safe_load(f))

3. 参数配置

Broker.__init__构造方法需要一个config参数,类型为python字典。为了方便起见,下面以YAML文件的形式给出它

listeners:
    default:
        max-connections: 50000
        type: tcp
    my-tcp-1:
        bind: 127.0.0.1:1883
    my-tcp-2:
        bind: 1.2.3.4:1884
        max-connections: 1000
    my-tcp-ssl-1:
        bind: 127.0.0.1:8885
        ssl: on
        cafile: /some/cafile
        capath: /some/folder
        capath: certificate data
        certfile: /some/certfile
        keyfile: /some/key
    my-ws-1:
        bind: 0.0.0.0:8080
        type: ws
timeout-disconnect-delay: 2
auth:
    plugins: ['auth.anonymous'] #List of plugins to activate for authentication among all registered plugins
    allow-anonymous: true / false
    password-file: /some/passwd_file

listeners : 可定义多个网络监听器,default 部分定义所有监听器的通用属性,每个监听器都有以下属性:

  • bind: IP 地址和端口号
  • max-connections: 最大监听客户端的数量,0代表无限制
  • type: 传输协议类型; 可以是 tcp 用于传统的TCP监听器,或者 ws 用于 websocket 传输 MQTT.
  • ssl enables (on) or disable secured connection over the transport protocol.
  • cafile, cadata, certfile and keyfile : SSL安全连接的必要参数。

auth:设置身份验证行为

  • plugins: 声明激活的插件列表,这些插件必须定义在hbmqtt.broker.pluginsentry point
  • allow-anonymous: 用于内部插件hbmqtt.plugins.authentication.AnonymousAuthPlugin ,决定是否允许匿名(无username)连接 broker。
  • password-file: 用于内部插件hbmqtt.plugins.authentication.FileAuthPlugin, 提供一个保存用户名+密码的文件路径
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Python中实现MQTT接入阿里云,需要使用Paho MQTT客户端和阿里云IoT Python SDK。以下是实现的步骤: 1.安装paho-mqtt和aliyun-iot-sdk-core第三方: ``` pip install paho-mqtt aliyun-iot-sdk-core ``` 2.创建一个MQTT客户端并连接到阿里云IoT: ```python import paho.mqtt.client as mqtt from aliyunsdkcore.client import AcsClient from aliyunsdkiot.request.v20170420 import RegisterDeviceRequest from aliyunsdkiot.request.v20170420 import PubRequest client = mqtt.Client(client_id="your_client_id") client.username_pw_set(username="your_product_key&your_device_name", password="your_device_secret") client.connect("your_product_key.iot-as-mqtt.cn-shanghai.aliyuncs.com", port=1883) ``` 3.注册设备并获取设备的Topic: ```python client = AcsClient("your_access_key_id", "your_access_key_secret", "cn-shanghai") request = RegisterDeviceRequest.RegisterDeviceRequest() request.set_ProductKey("your_product_key") request.set_DeviceName("your_device_name") response = client.do_action_with_exception(request) topic = response["Data"]["Device"]["Topic"] ``` 4.发布和订阅消息: ```python def on_message(client, userdata, msg): print(msg.topic + " " + str(msg.payload)) client.subscribe(topic) client.on_message = on_message request = PubRequest.PubRequest() request.set_ProductKey("your_product_key") request.set_TopicFullName(topic) request.set_MessageContent("hello world") client.publish(topic, payload="hello world", qos=0) ``` 以上是Python实现MQTT接入阿里云的简单示例,需要根据自己的实际情况进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值