文章目录
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字典类型,字段参考下文配置loop
:asyncio
模块中的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
andkeyfile
: SSL安全连接的必要参数。
auth:设置身份验证行为
plugins
: 声明激活的插件列表,这些插件必须定义在hbmqtt.broker.plugins
的entry pointallow-anonymous
: 用于内部插件hbmqtt.plugins.authentication.AnonymousAuthPlugin
,决定是否允许匿名(无username)连接 broker。password-file
: 用于内部插件hbmqtt.plugins.authentication.FileAuthPlugin
, 提供一个保存用户名+密码的文件路径