updating client documentation by converting rst format into google docstring params, including examples from reference file

pull/169/head
Andrew Mirsky 2025-05-21 21:59:12 -04:00
rodzic 0ad46ef783
commit 120ba1d699
Nie znaleziono w bazie danych klucza dla tego podpisu
ID klucza GPG: A98E67635CDF2C39
26 zmienionych plików z 526 dodań i 519 usunięć

Wyświetl plik

@ -1,21 +0,0 @@
### Changes included in this PR
*(Bug fix, feature, docs update, ...)*
### Current behavior
*Link to an open issue here...*
### New behavior
*If this is a feature change, describe the new behavior*
### Impact
*Describe breaking changes, including changes a users might need to make due to this PR*
### Checklist
1. [ ] Does your submission pass the existing tests?
2. [ ] Are there new tests that cover these additions/changes?
3. [ ] Have you linted your code locally before submission?

Wyświetl plik

@ -1,10 +1,9 @@
--- ---
name: Documentation request name: Documentation request
about: Suggest documentation for this project about: Suggest documentation for this project
title: '' title: ""
labels: documentation labels: documentation
assignees: '' assignees: ""
--- ---
**Describe the documentation you'd like** **Describe the documentation you'd like**

Wyświetl plik

@ -1,10 +1,9 @@
--- ---
name: Feature request name: Feature request
about: Suggest an idea for this project about: Suggest an idea for this project
title: '' title: ""
labels: enhancement labels: enhancement
assignees: '' assignees: ""
--- ---
**Is your feature request related to a problem? Please describe.** **Is your feature request related to a problem? Please describe.**

Wyświetl plik

@ -1,16 +1,15 @@
--- ---
name: Bug name: Bug
about: Describe this issue template's purpose here. about: Describe this issue template's purpose here.
title: '' title: ""
labels: bug labels: bug
assignees: '' assignees: ""
--- ---
When your issue is related to code that isn't working as expected, please When your issue is related to code that isn't working as expected, please
enable debug logs: enable debug logs:
``` python ```python
import logging import logging
logging.basicConfig(level=logging.DEBUG) logging.basicConfig(level=logging.DEBUG)
``` ```

Wyświetl plik

@ -0,0 +1,21 @@
### Changes included in this PR
_(Bug fix, feature, docs update, ...)_
### Current behavior
_Link to an open issue here..._
### New behavior
_If this is a feature change, describe the new behavior_
### Impact
_Describe breaking changes, including changes a users might need to make due to this PR_
### Checklist
1. [ ] Does your submission pass the existing tests?
2. [ ] Are there new tests that cover these additions/changes?
3. [ ] Have you linted your code locally before submission?

Wyświetl plik

@ -14,21 +14,21 @@ religion, or sexual identity and orientation.
Examples of behavior that contributes to creating a positive environment Examples of behavior that contributes to creating a positive environment
include: include:
* Using welcoming and inclusive language - Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences - Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism - Gracefully accepting constructive criticism
* Focusing on what is best for the community - Focusing on what is best for the community
* Showing empathy towards other community members - Showing empathy towards other community members
Examples of unacceptable behavior by participants include: Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or - The use of sexualized language or imagery and unwelcome sexual attention or
advances advances
* Trolling, insulting/derogatory comments, and personal or political attacks - Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment - Public or private harassment
* Publishing others' private information, such as a physical or electronic - Publishing others' private information, such as a physical or electronic
address, without explicit permission address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a - Other conduct which could reasonably be considered inappropriate in a
professional setting professional setting
## Our Responsibilities ## Our Responsibilities
@ -71,4 +71,3 @@ This Code of Conduct is adapted from the [Contributor Covenant][homepage], versi
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org [homepage]: https://www.contributor-covenant.org

Wyświetl plik

@ -8,48 +8,56 @@ The following is a set of guidelines for contributing to aMQTT on GitHub. These
### Requirements ### Requirements
1. python installed (at least one version, for developers it might be helpful to have multiple versions, e.g. 3.13 installed for testing purposes) 1. Install [uv](https://docs.astral.sh/uv/getting-started/installation/)
2. [uv](https://docs.astral.sh/uv/guides/install-python/) installed 2. Use `uv python install <version>` to install [3.10, 3.11, 3.12 or 3.13](https://docs.astral.sh/uv/guides/install-python/)
3. Fork repository (if you intend to open a pull request)
4. Clone repo `git clone git@github.com:<username>/amqtt.git`
5. Add repo to receive latest updates `git add upstream git@github.com:Yakio/amqtt.git`
### Testing the newest development version ### Installation
Create virtual environment with `UV` Create and start virtual environment with `UV`
```sh ```shell
uv venv --python 3.13.0 uv venv .venv --python 3.13.0
source .venv/bin/activate
``` ```
Install: Install the package with development (and doc) dependencies:
```sh ```shell
uv sync --no-dev uv pip install -e . --group dev --group doc
``` ```
Usage: Add git pre-commit checks (which parallel the CI checks):
```sh ```shell
pre-commit install
```
### Run
Run CLI commands:
```shell
uv run amqtt uv run amqtt
uv run amqtt_pub uv run amqtt_pub
uv run amqtt_sub uv run amqtt_sub
``` ```
### Setup development tools Run the test case suite:
Install with: ```shell
pytest
```sh
uv sync
``` ```
This will install all dependencies needed for development. Run the type checker and linters manually:
Afterwards you can use `pytest` etc. ```shell
pre-commit run --all-files
```
## Testing ## Testing
When adding a new feature please add a test along with the feature. The testing coverage should not decrease. When adding a new feature, please add corollary tests. The testing coverage should not decrease.
If you encounter a bug when using aMQTT which you then resolve, please reproduce the issue in a test as well. If you encounter a bug when using aMQTT which you then resolve, please reproduce the issue in a test as well.
## Style and linting
We use `ruff` at default settings. To avoid repeated pushes to satisfy our CI linter, you can use [pre-commit](https://pre-commit.com). Install the necessary hooks with `pre-commit install`.

Wyświetl plik

@ -1,6 +1,7 @@
The MIT License (MIT) The MIT License (MIT)
Copyright (c) 2015 Nicolas JOUANIN Copyright (c) 2015 Nicolas JOUANIN
Copyright (c) 2021 aMQTT Contributors (https://github.com/Yakifo/amqtt/graphs/contributors) Copyright (c) 2021 aMQTT Contributors (https://github.com/Yakifo/amqtt/graphs/contributors)
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy

Wyświetl plik

@ -9,7 +9,6 @@
![docs/assets/amqtt.svg](docs/assets/amqtt.svg) ![docs/assets/amqtt.svg](docs/assets/amqtt.svg)
`aMQTT` is an open source [MQTT](http://www.mqtt.org) broker[^1], natively implemented with Python's [asyncio](https://docs.python.org/3/library/asyncio.html). `aMQTT` is an open source [MQTT](http://www.mqtt.org) broker[^1], natively implemented with Python's [asyncio](https://docs.python.org/3/library/asyncio.html).
## Features ## Features
@ -22,7 +21,7 @@
- Authentication through password file - Authentication through password file
- Basic `$SYS` topics - Basic `$SYS` topics
## Getting started ## Installation
`amqtt` is available on [PyPI](https://pypi.python.org/pypi/amqtt) `amqtt` is available on [PyPI](https://pypi.python.org/pypi/amqtt)
@ -30,21 +29,23 @@
$ pip install amqtt $ pip install amqtt
``` ```
Documentation is available on [Read the Docs](http://amqtt.readthedocs.org/). ## Documentation
Available on [Read the Docs](http://amqtt.readthedocs.org/).
## Support
Bug reports, patches and suggestions welcome! Just [open an issue](https://github.com/Yakifo/amqtt/issues/new) or join the [gitter community](https://gitter.im/amqtt/community). Bug reports, patches and suggestions welcome! Just [open an issue](https://github.com/Yakifo/amqtt/issues/new) or join the [gitter community](https://gitter.im/amqtt/community).
## Python Version Compatibility
## Project Status and Roadmap
| Version | hbmqtt compatibility | Supported Python Versions | PyPi Release | | Version | hbmqtt compatibility | Supported Python Versions | PyPi Release |
|---------|----------------------|---------------------------|--------------| | ------- | -------------------- | ------------------------- | ------------ |
| 0.10.x | yes [^2] | 3.7 - 3.9 | 0.10.1 | | 0.10.x | yes [^2] | 3.7 - 3.9 | 0.10.1 |
| 0.11.x | no [^3] | 3.10 - 3.13 | 0.11.0 | | 0.11.x | no [^3] | 3.10 - 3.13 | 0.11.0 |
For a full feature roadmap, see ...
[^1]: Forked from [HBMQTT](https://github.com/beerfactory/hbmqtt) after it was deprecated by the original author. [^1]: Forked from [HBMQTT](https://github.com/beerfactory/hbmqtt) after it was deprecated by the original author.
[^2]: drop-in replacement [^2]: drop-in replacement
[^3]: module renamed and small API differences [^3]: module renamed and small API differences

Wyświetl plik

@ -28,10 +28,10 @@ from amqtt.utils import format_client_message, gen_client_id
from .plugins.manager import BaseContext, PluginManager from .plugins.manager import BaseContext, PluginManager
type _CONFIG_LISTENER = dict[str, int | bool | dict[str, Any]] type CONFIG_LISTENER = dict[str, int | bool | dict[str, Any]]
type _BROADCAST = dict[str, Session | str | bytes | int | None] type _BROADCAST = dict[str, Session | str | bytes | int | None]
_defaults: _CONFIG_LISTENER = { _defaults: CONFIG_LISTENER = {
"timeout-disconnect-delay": 2, "timeout-disconnect-delay": 2,
"auth": {"allow-anonymous": True, "password-file": None}, "auth": {"allow-anonymous": True, "password-file": None},
} }
@ -113,7 +113,7 @@ class BrokerContext(BaseContext):
def __init__(self, broker: "Broker") -> None: def __init__(self, broker: "Broker") -> None:
super().__init__() super().__init__()
self.config: _CONFIG_LISTENER | None = None self.config: CONFIG_LISTENER | None = None
self._broker_instance = broker self._broker_instance = broker
async def broadcast_message(self, topic: str, data: bytes, qos: int | None = None) -> None: async def broadcast_message(self, topic: str, data: bytes, qos: int | None = None) -> None:
@ -139,9 +139,10 @@ class BrokerContext(BaseContext):
class Broker: class Broker:
"""MQTT 3.1.1 compliant broker implementation. """MQTT 3.1.1 compliant broker implementation.
:param config: Example Yaml config Args:
:param loop: asyncio loop to use. Defaults to ``asyncio.get_event_loop()``. config: dictionary of configuration options (see config yaml format)
:param plugin_namespace: Plugin namespace to use when loading plugin entry_points. Defaults to ``amqtt.broker.plugins`` loop: asyncio loop. defaults to `asyncio.get_event_loop()`.
plugin_namespace: plugin namespace to use when loading plugin entry_points. defaults to `amqtt.broker.plugins`.
""" """
@ -157,7 +158,7 @@ class Broker:
def __init__( def __init__(
self, self,
config: _CONFIG_LISTENER | None = None, config: CONFIG_LISTENER | None = None,
loop: asyncio.AbstractEventLoop | None = None, loop: asyncio.AbstractEventLoop | None = None,
plugin_namespace: str | None = None, plugin_namespace: str | None = None,
) -> None: ) -> None:
@ -190,7 +191,7 @@ class Broker:
namespace = plugin_namespace or "amqtt.broker.plugins" namespace = plugin_namespace or "amqtt.broker.plugins"
self.plugins_manager = PluginManager(namespace, context, self._loop) self.plugins_manager = PluginManager(namespace, context, self._loop)
def _build_listeners_config(self, broker_config: _CONFIG_LISTENER) -> None: def _build_listeners_config(self, broker_config: CONFIG_LISTENER) -> None:
self.listeners_config = {} self.listeners_config = {}
try: try:
listeners_config = broker_config.get("listeners") listeners_config = broker_config.get("listeners")
@ -227,7 +228,6 @@ class Broker:
"""Start the broker to serve with the given configuration. """Start the broker to serve with the given configuration.
Start method opens network sockets and will start listening for incoming connections. Start method opens network sockets and will start listening for incoming connections.
This method is a *coroutine*.
""" """
try: try:
self._sessions.clear() self._sessions.clear()

Wyświetl plik

@ -89,10 +89,42 @@ class MQTTClient:
MQTTClient instances provides API for connecting to a broker and send/receive messages using the MQTT protocol. MQTTClient instances provides API for connecting to a broker and send/receive messages using the MQTT protocol.
:param client_id: MQTT client ID to use when connecting to the broker. Args:
If none, it will generated randomly by :func:`amqtt.utils.gen_client_id` client_id: MQTT client ID to use when connecting to the broker. If none, it will be generated randomly by `amqtt.utils.gen_client_id`
:param config: Client configuration config: Client configuration with the following keys:
:return: class instance
`keep_alive`: keep alive (in seconds) to send when connecting to the broker (defaults to `10` seconds). `MQTTClient` will _auto-ping_ the broker if no message is sent within the keep-alive interval. This avoids disconnection from the broker.
`ping_delay`: _auto-ping_ delay before keep-alive times out (defaults to `1` seconds).
`default_qos`: Default QoS (`0`) used by `publish()` if `qos` argument is not given.
`default_retain`: Default retain (`False`) used by `publish()` if `qos` argument is not given.
`auto_reconnect`: enable or disable auto-reconnect feature (defaults to `True`).
`reconnect_max_interval`: maximum interval (in seconds) to wait before two connection retries (defaults to `10`).
`reconnect_retries`: maximum number of connect retries (defaults to `2`). Negative value will cause client to reconnect infinitely.
Example:
```python
config = {
'keep_alive': 10,
'ping_delay': 1,
'default_qos': 0,
'default_retain': False,
'auto_reconnect': True,
'reconnect_max_interval': 5,
'reconnect_retries': 10,
'topics': {
'test': { 'qos': 1 },
'some_topic': { 'qos': 2, 'retain': True }
}
}
```
""" """
def __init__(self, client_id: str | None = None, config: dict[str, Any] | None = None) -> None: def __init__(self, client_id: str | None = None, config: dict[str, Any] | None = None) -> None:
@ -129,22 +161,22 @@ class MQTTClient:
At first, a network connection is established with the server At first, a network connection is established with the server
using the given protocol (``mqtt``, ``mqtts``, ``ws`` or ``wss``). using the given protocol (``mqtt``, ``mqtts``, ``ws`` or ``wss``).
Once the socket is connected, a Once the socket is connected, a
`CONNECT <http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718028>`_ [CONNECT](http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718028>)
message is sent with the requested information. message is sent with the requested information.
This method is a *coroutine*. Args:
uri: Broker URI connection, conforming to [MQTT URI scheme](https://github.com/mqtt/mqtt.github.io/wiki/URI-Scheme). default, ``uri`` config attribute.
cleansession: MQTT CONNECT clean session flag
cafile: server certificate authority file (optional, used for secured connection)
capath: server certificate authority path (optional, used for secured connection)
cadata: server certificate authority data (optional, used for secured connection)
additional_headers: a dictionary with additional http headers that should be sent on the initial connection (optional, used only with websocket connections)
:param uri: Broker URI connection, conforming to Returns:
`MQTT URI scheme <https://github.com/mqtt/mqtt.github.io/wiki/URI-Scheme>`_. [CONNACK](http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718033)'s return code
Uses ``uri`` config attribute by default.
:param cleansession: MQTT CONNECT clean session flag Raises:
:param cafile: server certificate authority file (optional, used for secured connection) `amqtt.client.ConnectException` if connection fails
:param capath: server certificate authority path (optional, used for secured connection)
:param cadata: server certificate authority data (optional, used for secured connection)
:param additional_headers: a dictionary with additional http headers that should be sent on the initial connection
(optional, used only with websocket connections)
:return: `CONNACK <http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718033>`_ return code
:raise: :class:`amqtt.client.ConnectException` if connection fails
""" """
additional_headers = additional_headers if additional_headers is not None else {} additional_headers = additional_headers if additional_headers is not None else {}
self.session = self._init_session(uri, cleansession, cafile, capath, cadata) self.session = self._init_session(uri, cleansession, cafile, capath, cadata)
@ -165,9 +197,9 @@ class MQTTClient:
async def disconnect(self) -> None: async def disconnect(self) -> None:
"""Disconnect from the connected broker. """Disconnect from the connected broker.
This method sends a `DISCONNECT <http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718090>` This method sends a [DISCONNECT](http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718090)
message and closes the network socket. message and closes the network socket.
This method is a *coroutine*.
""" """
await self.cancel_tasks() await self.cancel_tasks()
@ -197,15 +229,18 @@ class MQTTClient:
"""Reconnect a previously connected broker. """Reconnect a previously connected broker.
Reconnection tries to establish a network connection Reconnection tries to establish a network connection
and send a `CONNECT <http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718028>`_ message. and send a [CONNECT](http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718028) message.
Retries interval and attempts can be controlled with the ``reconnect_max_interval`` Retries interval and attempts can be controlled with the ``reconnect_max_interval``
and ``reconnect_retries`` configuration parameters. and ``reconnect_retries`` configuration parameters.
This method is a *coroutine*. Args:
cleansession: clean session flag used in MQTT CONNECT messages sent for reconnections.
:param cleansession: clean session flag used in MQTT CONNECT messages sent for reconnections. Returns:
:return: `CONNACK <http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718033>`_ return code [CONNACK](http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718033) return code
:raise: :class:`amqtt.client.ConnectException` if re-connection fails after max retries.
Raises:
`amqtt.client.ConnectException` if re-connection fails after max retries.
""" """
if self.session and self.session.transitions.is_connected(): if self.session and self.session.transitions.is_connected():
self.logger.warning("Client already connected") self.logger.warning("Client already connected")
@ -246,10 +281,9 @@ class MQTTClient:
async def ping(self) -> None: async def ping(self) -> None:
"""Ping the broker. """Ping the broker.
Send a MQTT `PINGREQ <http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718081>`_ Send a MQTT [PINGREQ](http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718081)
message for response. message for response.
This method is a *coroutine*.
""" """
if self.session and self._handler and self.session.transitions.is_connected(): if self.session and self._handler and self.session.transitions.is_connected():
await self._handler.mqtt_ping() await self._handler.mqtt_ping()
@ -271,16 +305,19 @@ class MQTTClient:
) -> OutgoingApplicationMessage: ) -> OutgoingApplicationMessage:
"""Publish a message to the broker. """Publish a message to the broker.
Send a MQTT `PUBLISH <http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718037>`_ Send a MQTT [PUBLISH](http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718037)
message and wait for acknowledgment depending on Quality Of Service message and wait for acknowledgment depending on Quality Of Service
This method is a *coroutine*. Args:
topic: topic name to which message data is published
message: payload message (as bytes) to send.
qos: requested publish quality of service : QOS_0, QOS_1 or QOS_2. Defaults to `default_qos` config parameter or QOS_0.
retain: retain flag. Defaults to ``default_retain`` config parameter or False.
ack_timeout: duration to wait for connection acknowledgment from broker.
Returns:
the message that was sent
:param topic: topic name to which message data is published
:param message: payload message (as bytes) to send.
:param qos: requested publish quality of service : QOS_0, QOS_1 or QOS_2. Defaults to ``default_qos``
config parameter or QOS_0.
:param retain: retain flag. Defaults to ``default_retain`` config parameter or False.
""" """
if self._handler is None: if self._handler is None:
msg = "Handler is not initialized." msg = "Handler is not initialized."
@ -317,21 +354,21 @@ class MQTTClient:
async def subscribe(self, topics: list[tuple[str, int]]) -> list[int]: async def subscribe(self, topics: list[tuple[str, int]]) -> list[int]:
"""Subscribe to topics. """Subscribe to topics.
Send a MQTT `SUBSCRIBE <http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718063>`_ Send a MQTT [SUBSCRIBE](http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718063)
message and wait for broker acknowledgment. message and wait for broker acknowledgment.
This method is a *coroutine*. Args:
topics: array of tuples containing topic pattern and QOS from `amqtt.mqtt.constants` to subscribe. For example:
:param topics: array of topics pattern to subscribe with associated QoS. ```python
:return: `SUBACK <http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718068>`_ message return code.
Example of ``topics`` argument expected structure:
::
[ [
("$SYS/broker/uptime", QOS_1), ("$SYS/broker/uptime", QOS_1),
("$SYS/broker/load/#", QOS_2), ("$SYS/broker/load/#", QOS_2),
] ]
```
Returns:
[SUBACK](http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718068) message return code.
""" """
if self._handler and self.session: if self._handler and self.session:
return await self._handler.mqtt_subscribe(topics, self.session.next_packet_id) return await self._handler.mqtt_subscribe(topics, self.session.next_packet_id)
@ -341,18 +378,15 @@ class MQTTClient:
async def unsubscribe(self, topics: list[str]) -> None: async def unsubscribe(self, topics: list[str]) -> None:
"""Unsubscribe from topics. """Unsubscribe from topics.
Send a MQTT `UNSUBSCRIBE <http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718072>`_ Send a MQTT [UNSUBSCRIBE](http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718072)
message and wait for broker `UNSUBACK <http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718077>`_ message and wait for broker [UNSUBACK](http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718077)
message. message.
This method is a *coroutine*. Args:
topics: array of topics to unsubscribe from.
:param topics: array of topics to unsubscribe from. ```
Example of ``topics`` argument expected structure:
::
["$SYS/broker/uptime", "$SYS/broker/load/#"] ["$SYS/broker/uptime", "$SYS/broker/load/#"]
```
""" """
if self._handler and self.session: if self._handler and self.session:
await self._handler.mqtt_unsubscribe(topics, self.session.next_packet_id) await self._handler.mqtt_unsubscribe(topics, self.session.next_packet_id)
@ -363,12 +397,14 @@ class MQTTClient:
Deliver next message received from the broker. If no message is available, this methods waits until next message arrives Deliver next message received from the broker. If no message is available, this methods waits until next message arrives
or ``timeout_duration`` occurs. or ``timeout_duration`` occurs.
This method is a *coroutine*. Args:
timeout_duration: maximum number of seconds to wait before returning. If not specified or None, there is no limit.
:param timeout_duration: maximum number of seconds to wait before returning. Returns:
If not specified or None, there is no limit. instance of `amqtt.session.ApplicationMessage` containing received message information flow.
:return: instance of :class:`amqtt.session.ApplicationMessage` containing received message information flow.
:raises: :class:`asyncio.TimeoutError` if timeout occurs before a message is delivered Raises:
`asyncio.TimeoutError` if timeout occurs before a message is delivered
""" """
if self._handler is None: if self._handler is None:
msg = "Handler is not initialized." msg = "Handler is not initialized."

Wyświetl plik

@ -1,4 +1,3 @@
/* /*
https://coolors.co/568e83-f5fbef-84c318-9684a1-161925 https://coolors.co/568e83-f5fbef-84c318-9684a1-161925
https://coolors.co/2ec0f9-67aaf9-9bbdf9-c4e0f9-b95f89 https://coolors.co/2ec0f9-67aaf9-9bbdf9-c4e0f9-b95f89
@ -9,9 +8,20 @@ https://coolors.co/e6c229-f17105-d11149-6610f2-1a8fe3
*/ */
.md-header { .md-header {
background: #D11149 background: #d11149;
} }
nav.md-tabs { nav.md-tabs {
display: none; display: none;
} }
h2.doc-heading-parameter {
font-size: 16px;
}
.doc-md-description {
font-size: 16px;
display: block;
}

80
docs/changelog.md 100644
Wyświetl plik

@ -0,0 +1,80 @@
# Changelog
## 0.11.0
- Removed hbmqtt compatibility, importing amqtt is now mandatory
- Removed loop parameter from all functions
- Python 3.10 to 3.13 compatibility
- Fixed a major bug in plugin api, see [PR #92](https://github.com/Yakifo/amqtt/pull/92)
- Migrated from `docopts` to `typer`
## 0.10.0
- First release under new package name: amqtt
- Reworked unit tests
- Dropped support for python3.5 and earlier
- Added support for python3.8 and 3.9
- Pass in loop to PluginManager, from [PR #126](https://github.com/beerfactory/hbmqtt/pull/126)
- Fixes taboo topic checking without session username, from [PR #151](https://github.com/beerfactory/hbmqtt/pull/151)
- Move scripts module into hbmqtt module, from [PR #167](https://github.com/beerfactory/hbmqtt/pull/167)
- Download mosquitto certificate on the fly
- Importing `hbmqtt` is deprecated, use `amqtt`
- Security fix: If an attacker could produce a KeyError inside an authentication plugin, the authentication was accepted instead of rejected
## 0.9.5
- fixes: [milestone 0.9.5](https://github.com/njouanin/hbmqtt/milestone/11?closed=1)
- fixes: [milestone 0.9.3](https://github.com/njouanin/hbmqtt/milestone/10?closed=1)
## 0.9.2
- fixes: [milestone 0.9.2](https://github.com/beerfactory/hbmqtt/milestone/9?closed=1)
## 0.9.1
- See commit log
## 0.9.0
- fixes: [milestone 0.9.0](https://github.com/beerfactory/hbmqtt/milestone/8?closed=1)
- improve plugin performance
- support Python 3.6
- upgrade to `websockets` 3.3.0
## 0.8.0
- fixes: [milestone 0.8.0](https://github.com/njouanin/hbmqtt/milestone/7?closed=1)
## 0.7.3
- fix deliver message client method to raise TimeoutError ([#40](https://github.com/beerfactory/hbmqtt/issues/40))
- fix topic filter matching in broker ([#41](https://github.com/beerfactory/hbmqtt/issues/41))
Version 0.7.2 has been jumped due to troubles with pypi...
## 0.7.1
- Fix [duplicated $SYS topic name](https://github.com/beerfactory/hbmqtt/issues/37)
## 0.7.0
- Fix a [series of issues](https://github.com/beerfactory/hbmqtt/issues?q=milestone%3A0.7+is%3Aclosed) reported by [Christoph Krey](https://github.com/ckrey)
## 0.6.3
- Fix issue [#22](https://github.com/beerfactory/hbmqtt/issues/22)
## 0.6.2
- Fix issue [#20](https://github.com/beerfactory/hbmqtt/issues/20) (`mqtt` subprotocol was missing)
- Upgrade to `websockets` 3.0
## 0.6.1
- Fix issue [#19](https://github.com/beerfactory/hbmqtt/issues/19)
## 0.6
- Added compatibility with Python 3.5
- Rewritten documentation
- Add command-line tools `amqtt`, `amqtt_pub` and `amqtt_sub`

Wyświetl plik

@ -1,97 +0,0 @@
Changelog
=========
0.11.0
-------------------------
* Removed hbmqtt compatibility, importing amqtt is now mandatory
* Removed loop parameter from all functions
* Python 3.10 to 3.13 compatibility
* Fixed a major bug in plugin api, see https://github.com/Yakifo/amqtt/pull/92
* Migrated from `docopts` to `typer`
0.10.0
-------------------
* First release under new package name: amqtt
* Reworked unit tests
* Dropped support for python3.5 and earlier
* Added support for python3.8 and 3.9
* Pass in loop to PluginManager, from https://github.com/beerfactory/hbmqtt/pull/126
* Fixes taboo topic checking without session username, from https://github.com/beerfactory/hbmqtt/pull/151
* Move scripts module into hbmqtt module, from https://github.com/beerfactory/hbmqtt/pull/167
* Download mosquitto certificate on the fly
* Importing `hbmqtt` is deprecated, use `amqtt`
* Security fix: If an attacker could produce a KeyError inside an authentication plugin, the authentication was accepted instead of rejected
0.9.5
-----
* fixes: `milestone 0.9.5 <https://github.com/njouanin/hbmqtt/milestone/11?closed=1>`_
* fixes: `milestone 0.9.3 <https://github.com/njouanin/hbmqtt/milestone/10?closed=1>`_
0.9.2
-----
* fixes: `milestone 0.9.2 <https://github.com/beerfactory/hbmqtt/milestone/9?closed=1>`_
0.9.1
-----
* See commit log
0.9.0
-----
* fixes: `milestone 0.9.0 <https://github.com/beerfactory/hbmqtt/milestone/8?closed=1>`_
* improve plugin performance
* support Python 3.6
* upgrade to ``websockets`` 3.3.0
0.8.0
-----
* fixes:`milestone 0.8.0 <https://github.com/njouanin/hbmqtt/milestone/7?closed=1>`_
0.7.3
-----
* fix deliver message client method to raise TimeoutError (`#40 <https://github.com/beerfactory/hbmqtt/issues/40>`_)
* fix topic filter matching in broker (`#41 <https://github.com/beerfactory/hbmqtt/issues/41>`_)
Version 0.7.2 has been jumped due to troubles with pypi...
0.7.1
-----
* Fix `duplicated $SYS topic name <https://github.com/beerfactory/hbmqtt/issues/37>`_ .
0.7.0
-----
* Fix a `series of issues <https://github.com/beerfactory/hbmqtt/issues?q=milestone%3A0.7+is%3Aclosed>`_ reported by `Christoph Krey <https://github.com/ckrey>`_
0.6.3
-----
* Fix issue `#22 <https://github.com/beerfactory/hbmqtt/issues/22>`_.
0.6.2
-----
* Fix issue `#20 <https://github.com/beerfactory/hbmqtt/issues/20>`_ (``mqtt`` subprotocol was missing).
* Upgrade to ``websockets`` 3.0.
0.6.1
-----
* Fix issue `#19 <https://github.com/beerfactory/hbmqtt/issues/19>`_
0.6
---
* Added compatibility with Python 3.5.
* Rewritten documentation.
* Add command-line tools :doc:`references/amqtt`, :doc:`references/amqtt_pub` and :doc:`references/amqtt_sub`.

Wyświetl plik

@ -0,0 +1 @@
--8<-- "CODE_OF_CONDUCT.md"

Wyświetl plik

@ -0,0 +1 @@
--8<-- "CONTRIBUTING.md"

1
docs/license.md 100644
Wyświetl plik

@ -0,0 +1 @@
--8<-- "LICENSE.md"

Wyświetl plik

@ -2,9 +2,9 @@
`aMQTT` is an open source `MQTT` client and broker implementation; these can be integrated into other projects using the appropriate APIs. To get started, three command-line scripts are also installed along with the package: `aMQTT` is an open source `MQTT` client and broker implementation; these can be integrated into other projects using the appropriate APIs. To get started, three command-line scripts are also installed along with the package:
* `amqtt` - the MQTT broker - `amqtt` - the MQTT broker
* `amqtt_pub` - an MQTT client to publish messages - `amqtt_pub` - an MQTT client to publish messages
* `amqtt_sub` - an MQTT client to listen for messages - `amqtt_sub` - an MQTT client to listen for messages
To install the `aMQTT` package: To install the `aMQTT` package:

Wyświetl plik

@ -44,44 +44,45 @@ Using the `-c` argument allows for configuration with a YAML structured file. Th
Defines network listeners for the MQTT server (list). Defines network listeners for the MQTT server (list).
#### `<interface name>` #### `<interface name>`
`default` for parameters used across all interfaces _or_ name for the specific interface (mapping). `default` for parameters used across all interfaces _or_ name for the specific interface (mapping).
Each entry supports these parameters: Each entry supports these parameters:
- `bind` (string, *required*) - `bind` (string, _required_)
Address and port to bind to, in the form `host:port` (e.g., `0.0.0.0:1883`). Address and port to bind to, in the form `host:port` (e.g., `0.0.0.0:1883`).
- `type` (string, *required*) - `type` (string, _required_)
Protocol type. Typically `"tcp"` or `"ws"`. Protocol type. Typically `"tcp"` or `"ws"`.
- `max-connections` (integer, *required*) - `max-connections` (integer, _required_)
Maximum number of clients that can connect to this interface Maximum number of clients that can connect to this interface
- `ssl` (string, *optional, default: `off`*) - `ssl` (string, _optional, default: `off`_)
Disable (`off`) SSL/TLS or enable (`on`) with one of `cafile`, `capath`, `cadata` or `certfile`/`keyfile`. Disable (`off`) SSL/TLS or enable (`on`) with one of `cafile`, `capath`, `cadata` or `certfile`/`keyfile`.
- `cafile` (string, *optional*) - `cafile` (string, _optional_)
Path to a file of concatenated CA certificates in PEM format. See [Certificates](https://docs.python.org/3/library/ssl.html#ssl-certificates) for more info. Path to a file of concatenated CA certificates in PEM format. See [Certificates](https://docs.python.org/3/library/ssl.html#ssl-certificates) for more info.
- `capath` (string, *optional*) - `capath` (string, _optional_)
Path to a directory containing several CA certificates in PEM format, following an [OpenSSL specific layout](https://docs.openssl.org/master/man3/SSL_CTX_load_verify_locations/). Path to a directory containing several CA certificates in PEM format, following an [OpenSSL specific layout](https://docs.openssl.org/master/man3/SSL_CTX_load_verify_locations/).
- `cadata` (string, *optional*) - `cadata` (string, _optional_)
Either an ASCII string of one or more PEM-encoded certificates or a bytes-like object of DER-encoded certificates Either an ASCII string of one or more PEM-encoded certificates or a bytes-like object of DER-encoded certificates
- `certfile` (string, *optional*) - `certfile` (string, _optional_)
Path to a single file in PEM format containing the certificate as well as any number of CA certificates needed to establish the certificate's authenticity Path to a single file in PEM format containing the certificate as well as any number of CA certificates needed to establish the certificate's authenticity
- `keyfile` (string, *optional*) - `keyfile` (string, _optional_)
A file containing the private key. Otherwise the private key will be taken from certfile as well A file containing the private key. Otherwise the private key will be taken from certfile as well
### timeout-disconnect-delay ### timeout-disconnect-delay
Client disconnect timeout without a keep-alive (integer, *optional*) Client disconnect timeout without a keep-alive (integer, _optional_)
### plugins ### plugins
Entry points for optional functionality (*list of strings*); included plugins are: Entry points for optional functionality (_list of strings_); included plugins are:
- `auth_file` – Enables file-based authentication - `auth_file` – Enables file-based authentication
- `auth_anonymous` – Enables anonymous access - `auth_anonymous` – Enables anonymous access
@ -95,10 +96,10 @@ Entry points for optional functionality (*list of strings*); included plugins ar
Authentication and authorization settings (mapping). Authentication and authorization settings (mapping).
- `allow-anonymous` (boolean, *optional for `auth_anonymous` plugin*) - `allow-anonymous` (boolean, _optional for `auth_anonymous` plugin_)
Allow (`true`) or prevent (`false`) anonymous client to connections. Allow (`true`) or prevent (`false`) anonymous client to connections.
- `password-file` (string, *required for `auth_file` plugin*) - `password-file` (string, _required for `auth_file` plugin_)
Path to file which includes `username:password` pair, one per line. The password should be encoded using sha-512 with `mkpasswd -m sha-512` or: Path to file which includes `username:password` pair, one per line. The password should be encoded using sha-512 with `mkpasswd -m sha-512` or:
```python ```python
@ -112,7 +113,7 @@ print(sha512_crypt.hash(passwd))
### sys-interval ### sys-interval
Interval in seconds to publish system statistics to `$SYS` topics (integer, *optional for `broker_sys` plugin, defaults to TBD*). Interval in seconds to publish system statistics to `$SYS` topics (integer, _optional for `broker_sys` plugin, defaults to TBD_).
## Configuration example ## Configuration example
@ -150,16 +151,16 @@ auth:
The `listeners` section defines 5 bindings: The `listeners` section defines 5 bindings:
* `my-tcp-1`: an unsecured TCP listener on port 1883 allowing `500` clients connections simultaneously - `my-tcp-1`: an unsecured TCP listener on port 1883 allowing `500` clients connections simultaneously
* `my-tcp-2`: an unsecured TCP listener on port 1884 allowing `1000` client connections - `my-tcp-2`: an unsecured TCP listener on port 1884 allowing `1000` client connections
* `my-tcp-ssl-1`: a secured TCP listener on port 8883 allowing `500` clients connections simultaneously - `my-tcp-ssl-1`: a secured TCP listener on port 8883 allowing `500` clients connections simultaneously
* `my-ws-1`: an unsecured websocket listener on port 9001 allowing `500` clients connections simultaneously - `my-ws-1`: an unsecured websocket listener on port 9001 allowing `500` clients connections simultaneously
* `my-wss-1`: a secured websocket listener on port 9003 allowing `500` - `my-wss-1`: a secured websocket listener on port 9003 allowing `500`
The plugins section enables: The plugins section enables:
* `auth_file` plugin, requiring `password-file` to be defined in the `auth` section - `auth_file` plugin, requiring `password-file` to be defined in the `auth` section
* `broker_sys` plugin, requiring `sys_interval` to be defined - `broker_sys` plugin, requiring `sys_interval` to be defined
Authentication allows anonymous logins and password file based authentication. Password files are required to be text files containing user name and password in the form of: Authentication allows anonymous logins and password file based authentication. Password files are required to be text files containing user name and password in the form of:

Wyświetl plik

@ -48,34 +48,38 @@ Note that for simplicity, `amqtt_pub` uses mostly the same argument syntax as [m
If `-c` argument is given, `amqtt_pub` will read specific MQTT settings for the given configuration file. This file must be a valid [YAML](http://yaml.org/) file which may contain the following configuration elements: If `-c` argument is given, `amqtt_pub` will read specific MQTT settings for the given configuration file. This file must be a valid [YAML](http://yaml.org/) file which may contain the following configuration elements:
* `keep_alive`: Keep-alive timeout sent to the broker. Defaults to `10` seconds. - `keep_alive`: Keep-alive timeout sent to the broker. Defaults to `10` seconds.
* `ping_delay`: Auto-ping delay before keep-alive timeout. Defaults to 1. Setting to `0` will disable to 0 and may lead to broker disconnection. - `ping_delay`: Auto-ping delay before keep-alive timeout. Defaults to 1. Setting to `0` will disable to 0 and may lead to broker disconnection.
* `default_qos`: Default QoS for messages published. Defaults to 0. - `default_qos`: Default QoS for messages published. Defaults to 0.
* `default_retain`: Default retain value to messages published. Defaults to `false`. - `default_retain`: Default retain value to messages published. Defaults to `false`.
* `auto_reconnect`: Enable or disable auto-reconnect if connection with the broker is interrupted. Defaults to `false`. - `auto_reconnect`: Enable or disable auto-reconnect if connection with the broker is interrupted. Defaults to `false`.
* `reconnect_retries`: Maximum reconnection retries. Defaults to `2`. Negative value will cause client to reconnect infinitely. - `reconnect_retries`: Maximum reconnection retries. Defaults to `2`. Negative value will cause client to reconnect infinitely.
* `reconnect_max_interval`: Maximum interval between 2 connection retry. Defaults to `10`. - `reconnect_max_interval`: Maximum interval between 2 connection retry. Defaults to `10`.
## Examples ## Examples
Examples below are adapted from [mosquitto_pub](http://mosquitto.org/man/mosquitto_pub-1.html) documentation. Examples below are adapted from [mosquitto_pub](http://mosquitto.org/man/mosquitto_pub-1.html) documentation.
Publish temperature information to localhost with QoS 1: Publish temperature information to localhost with QoS 1:
```bash ```bash
amqtt_pub --url mqtt://localhost -t sensors/temperature -m 32 -q 1 amqtt_pub --url mqtt://localhost -t sensors/temperature -m 32 -q 1
``` ```
Publish timestamp and temperature information to a remote host on a non-standard port and QoS 0: Publish timestamp and temperature information to a remote host on a non-standard port and QoS 0:
```bash ```bash
amqtt_pub --url mqtt://192.168.1.1:1885 -t sensors/temperature -m "1266193804 32" amqtt_pub --url mqtt://192.168.1.1:1885 -t sensors/temperature -m "1266193804 32"
``` ```
Publish light switch status. Message is set to retained because there may be a long period of time between light switch events: Publish light switch status. Message is set to retained because there may be a long period of time between light switch events:
```bash ```bash
amqtt_pub --url mqtt://localhost -r -t switches/kitchen_lights/status -m "on" amqtt_pub --url mqtt://localhost -r -t switches/kitchen_lights/status -m "on"
``` ```
Send the contents of a file in two ways: Send the contents of a file in two ways:
```bash ```bash
amqtt_pub --url mqtt://localhost -t my/topic -f ./data amqtt_pub --url mqtt://localhost -t my/topic -f ./data
@ -83,6 +87,7 @@ amqtt_pub --url mqtt://localhost -t my/topic -s < ./data
``` ```
Publish temperature information to localhost with QoS 1 over mqtt encapsulated in a websocket connection and additional headers: Publish temperature information to localhost with QoS 1 over mqtt encapsulated in a websocket connection and additional headers:
```bash ```bash
amqtt_pub --url wss://localhost -t sensors/temperature -m 32 -q 1 --extra-headers '{"Authorization": "Bearer <token>"}' amqtt_pub --url wss://localhost -t sensors/temperature -m 32 -q 1 --extra-headers '{"Authorization": "Bearer <token>"}'
``` ```

Wyświetl plik

@ -43,29 +43,32 @@ Note that for simplicity, `amqtt_sub` uses mostly the same argument syntax as [m
If `-c` argument is given, `amqtt_sub` will read specific MQTT settings for the given configuration file. This file must be a valid [YAML](http://yaml.org/) file which may contain the following configuration elements: If `-c` argument is given, `amqtt_sub` will read specific MQTT settings for the given configuration file. This file must be a valid [YAML](http://yaml.org/) file which may contain the following configuration elements:
* `keep_alive`: Keep-alive timeout sent to the broker. Defaults to `10` seconds. - `keep_alive`: Keep-alive timeout sent to the broker. Defaults to `10` seconds.
* `ping_delay`: Auto-ping delay before keep-alive timeout. Defaults to 1. Setting to `0` will disable to 0 and may lead to broker disconnection. - `ping_delay`: Auto-ping delay before keep-alive timeout. Defaults to 1. Setting to `0` will disable to 0 and may lead to broker disconnection.
* `default_qos`: Default QoS for messages published. Defaults to 0. - `default_qos`: Default QoS for messages published. Defaults to 0.
* `default_retain`: Default retain value to messages published. Defaults to `false`. - `default_retain`: Default retain value to messages published. Defaults to `false`.
* `auto_reconnect`: Enable or disable auto-reconnect if connection with the broker is interrupted. Defaults to `false`. - `auto_reconnect`: Enable or disable auto-reconnect if connection with the broker is interrupted. Defaults to `false`.
* `reconnect_retries`: Maximum reconnection retries. Defaults to `2`. Negative value will cause client to reconnect infinitely. - `reconnect_retries`: Maximum reconnection retries. Defaults to `2`. Negative value will cause client to reconnect infinitely.
* `reconnect_max_interval`: Maximum interval between 2 connection retry. Defaults to `10`. - `reconnect_max_interval`: Maximum interval between 2 connection retry. Defaults to `10`.
## Examples ## Examples
Examples below are adapted from [mosquitto_sub](http://mosquitto.org/man/mosquitto_sub-1.html) documentation. Examples below are adapted from [mosquitto_sub](http://mosquitto.org/man/mosquitto_sub-1.html) documentation.
Subscribe with QoS 0 to all messages published under $SYS/: Subscribe with QoS 0 to all messages published under $SYS/:
```bash ```bash
amqtt_sub --url mqtt://localhost -t '$SYS/#' -q 0 amqtt_sub --url mqtt://localhost -t '$SYS/#' -q 0
``` ```
Subscribe to 10 messages with QoS 2 from /#: Subscribe to 10 messages with QoS 2 from /#:
```bash ```bash
amqtt_sub --url mqtt://localhost -t # -q 2 -n 10 amqtt_sub --url mqtt://localhost -t # -q 2 -n 10
``` ```
Subscribe with QoS 0 to all messages published under $SYS/ over mqtt encapsulated in a websocket connection and additional headers: Subscribe with QoS 0 to all messages published under $SYS/ over mqtt encapsulated in a websocket connection and additional headers:
```bash ```bash
amqtt_sub --url wss://localhost -t '$SYS/#' -q 0 --extra-headers '{"Authorization": "Bearer <token>"}' amqtt_sub --url wss://localhost -t '$SYS/#' -q 0 --extra-headers '{"Authorization": "Bearer <token>"}'
``` ```

Wyświetl plik

@ -80,25 +80,28 @@ topic-check:
The `listeners` section allows defining network listeners which must be started by the `Broker`. Several listeners can be setup. `default` subsection defines common attributes for all listeners. Each listener can have the following settings: The `listeners` section allows defining network listeners which must be started by the `Broker`. Several listeners can be setup. `default` subsection defines common attributes for all listeners. Each listener can have the following settings:
* `bind`: IP address and port binding. - `bind`: IP address and port binding.
* `max-connections`: Set maximum number of active connection for the listener. `0` means no limit. - `max-connections`: Set maximum number of active connection for the listener. `0` means no limit.
* `type`: transport protocol type; can be `tcp` for classic TCP listener or `ws` for MQTT over websocket. - `type`: transport protocol type; can be `tcp` for classic TCP listener or `ws` for MQTT over websocket.
* `ssl`: enables (`on`) or disable secured connection over the transport protocol. - `ssl`: enables (`on`) or disable secured connection over the transport protocol.
* `cafile`, `cadata`, `certfile` and `keyfile`: mandatory parameters for SSL secured connections. - `cafile`, `cadata`, `certfile` and `keyfile`: mandatory parameters for SSL secured connections.
The `auth` section setup authentication behaviour: The `auth` section setup authentication behaviour:
* `plugins`: defines the list of activated plugins. Note the plugins must be defined in the `amqtt.broker.plugins` [entry point](https://pythonhosted.org/setuptools/setuptools.html#dynamic-discovery-of-services-and-plugins). - `plugins`: defines the list of activated plugins. Note the plugins must be defined in the `amqtt.broker.plugins` [entry point](https://pythonhosted.org/setuptools/setuptools.html#dynamic-discovery-of-services-and-plugins).
* `allow-anonymous`: used by the internal `amqtt.plugins.authentication.AnonymousAuthPlugin` plugin. This parameter enables (`on`) or disable anonymous connection, i.e. connection without username. - `allow-anonymous`: used by the internal `amqtt.plugins.authentication.AnonymousAuthPlugin` plugin. This parameter enables (`on`) or disable anonymous connection, i.e. connection without username.
* `password-file`: used by the internal `amqtt.plugins.authentication.FileAuthPlugin` plugin. This parameter gives to path of the password file to load for authenticating users. - `password-file`: used by the internal `amqtt.plugins.authentication.FileAuthPlugin` plugin. This parameter gives to path of the password file to load for authenticating users.
The `topic-check` section setup access control policies for publishing and subscribing to topics: The `topic-check` section setup access control policies for publishing and subscribing to topics:
* `enabled`: set to true if you want to impose an access control policy. Otherwise, set it to false. - `enabled`: set to true if you want to impose an access control policy. Otherwise, set it to false.
* `plugins`: defines the list of activated plugins. Note the plugins must be defined in the `amqtt.broker.plugins` [entry point](https://pythonhosted.org/setuptools/setuptools.html#dynamic-discovery-of-services-and-plugins). - `plugins`: defines the list of activated plugins. Note the plugins must be defined in the `amqtt.broker.plugins` [entry point](https://pythonhosted.org/setuptools/setuptools.html#dynamic-discovery-of-services-and-plugins).
* additional parameters: depending on the plugin used for access control, additional parameters should be added. - additional parameters: depending on the plugin used for access control, additional parameters should be added.
* In case of `topic_acl` plugin, the Access Control List (ACL) must be defined in the parameter `acl`. - In case of `topic_acl` plugin, the Access Control List (ACL) must be defined in the parameter `acl`.
* For each username, a list with the allowed topics must be defined. - For each username, a list with the allowed topics must be defined.
* If the client logs in anonymously, the `anonymous` entry within the ACL is used in order to grant/deny subscriptions. - If the client logs in anonymously, the `anonymous` entry within the ACL is used in order to grant/deny subscriptions.
::: amqtt.broker.Broker
[^1]: See [PyYAML](http://pyyaml.org/wiki/PyYAMLDocumentation) for loading YAML files as Python dict. [^1]: See [PyYAML](http://pyyaml.org/wiki/PyYAMLDocumentation) for loading YAML files as Python dict.

Wyświetl plik

@ -104,6 +104,7 @@ Both do the same job. `test_coro()` publishes 3 messages in sequence. `test_coro
The difference appears when looking at the sequence of MQTT messages sent. The difference appears when looking at the sequence of MQTT messages sent.
`test_coro()` achieves: `test_coro()` achieves:
``` ```
amqtt/YDYY;NNRpYQSy3?o -out-> PublishPacket(ts=2015-11-11 21:54:48.843901, fixed=MQTTFixedHeader(length=28, flags=0x0), variable=PublishVariableHeader(topic=a/b, packet_id=None), payload=PublishPayload(data="b'TEST MESSAGE WITH QOS_0'")) amqtt/YDYY;NNRpYQSy3?o -out-> PublishPacket(ts=2015-11-11 21:54:48.843901, fixed=MQTTFixedHeader(length=28, flags=0x0), variable=PublishVariableHeader(topic=a/b, packet_id=None), payload=PublishPayload(data="b'TEST MESSAGE WITH QOS_0'"))
amqtt/YDYY;NNRpYQSy3?o -out-> PublishPacket(ts=2015-11-11 21:54:48.844152, fixed=MQTTFixedHeader(length=30, flags=0x2), variable=PublishVariableHeader(topic=a/b, packet_id=1), payload=PublishPayload(data="b'TEST MESSAGE WITH QOS_1'")) amqtt/YDYY;NNRpYQSy3?o -out-> PublishPacket(ts=2015-11-11 21:54:48.844152, fixed=MQTTFixedHeader(length=30, flags=0x2), variable=PublishVariableHeader(topic=a/b, packet_id=1), payload=PublishPayload(data="b'TEST MESSAGE WITH QOS_1'"))
@ -115,6 +116,7 @@ amqtt/YDYY;NNRpYQSy3?o <-in-- PubcompPacket(ts=2015-11-11 21:54:49.092514, fixed
``` ```
while `test_coro2()` runs: while `test_coro2()` runs:
``` ```
amqtt/LYRf52W[56SOjW04 -out-> PublishPacket(ts=2015-11-11 21:54:48.466123, fixed=MQTTFixedHeader(length=28, flags=0x0), variable=PublishVariableHeader(topic=a/b, packet_id=None), payload=PublishPayload(data="b'TEST MESSAGE WITH QOS_0'")) amqtt/LYRf52W[56SOjW04 -out-> PublishPacket(ts=2015-11-11 21:54:48.466123, fixed=MQTTFixedHeader(length=28, flags=0x0), variable=PublishVariableHeader(topic=a/b, packet_id=None), payload=PublishPayload(data="b'TEST MESSAGE WITH QOS_0'"))
amqtt/LYRf52W[56SOjW04 -out-> PublishPacket(ts=2015-11-11 21:54:48.466432, fixed=MQTTFixedHeader(length=30, flags=0x2), variable=PublishVariableHeader(topic=a/b, packet_id=1), payload=PublishPayload(data="b'TEST MESSAGE WITH QOS_1'")) amqtt/LYRf52W[56SOjW04 -out-> PublishPacket(ts=2015-11-11 21:54:48.466432, fixed=MQTTFixedHeader(length=30, flags=0x2), variable=PublishVariableHeader(topic=a/b, packet_id=1), payload=PublishPayload(data="b'TEST MESSAGE WITH QOS_1'"))
@ -127,54 +129,4 @@ amqtt/LYRf52W[56SOjW04 <-in-- PubcompPacket(ts=2015-11-11 21:54:48.713107, fixed
Both coroutines have the same results except that `test_coro2()` manages messages flow in parallel which may be more efficient. Both coroutines have the same results except that `test_coro2()` manages messages flow in parallel which may be more efficient.
## Reference ::: amqtt.client.MQTTClient
### MQTTClient API
The `amqtt.client` module provides the following methods in the `MQTTClient` class:
- `connect()`: Connect to a remote broker
- `disconnect()`: Disconnect from the broker
- `reconnect()`: Reconnect to the broker
- `ping()`: Send a PING request to the broker
- `publish()`: Publish a message to the broker
- `subscribe()`: Subscribe to one or more topics
- `unsubscribe()`: Unsubscribe from one or more topics
- `deliver_message()`: Receive the next message from the broker
### MQTTClient configuration
The `MQTTClient` `__init__` method accepts a `config` parameter which allows setup of behavior and default settings. This argument must be a Python dict object which may contain the following entries:
* `keep_alive`: keep alive (in seconds) to send when connecting to the broker (defaults to `10` seconds). `MQTTClient` will *auto-ping* the broker if no message is sent within the keep-alive interval. This avoids disconnection from the broker.
* `ping_delay`: *auto-ping* delay before keep-alive times out (defaults to `1` seconds).
* `default_qos`: Default QoS (`0`) used by `publish()` if `qos` argument is not given.
* `default_retain`: Default retain (`False`) used by `publish()` if `qos` argument is not given.
* `auto_reconnect`: enable or disable auto-reconnect feature (defaults to `True`).
* `reconnect_max_interval`: maximum interval (in seconds) to wait before two connection retries (defaults to `10`).
* `reconnect_retries`: maximum number of connect retries (defaults to `2`). Negative value will cause client to reconnect infinitely.
Default QoS and default retain can also be overridden by adding a `topics` with may contain QoS and retain values for specific topics. See the following example:
```python
config = {
'keep_alive': 10,
'ping_delay': 1,
'default_qos': 0,
'default_retain': False,
'auto_reconnect': True,
'reconnect_max_interval': 5,
'reconnect_retries': 10,
'topics': {
'test': { 'qos': 1 },
'some_topic': { 'qos': 2, 'retain': True }
}
}
```
With this setting any message published will be set with QOS_0 and retain flag unset except for:
* messages sent to `test` topic: they will be sent with QOS_1
* messages sent to `some_topic` topic: they will be sent with QOS_2 and retain flag set
In any case, the `qos` and `retain` argument values passed to method `publish()` will override these settings.

Wyświetl plik

@ -4,12 +4,12 @@ Reference documentation for aMQTT console scripts and programming API.
## Console scripts ## Console scripts
* [amqtt_pub](amqtt_pub.md): MQTT client for publishing messages to a broker - [amqtt_pub](amqtt_pub.md): MQTT client for publishing messages to a broker
* [amqtt_sub](amqtt_sub.md): MQTT client for subscribing to topics and retrieved published messages - [amqtt_sub](amqtt_sub.md): MQTT client for subscribing to topics and retrieved published messages
* [amqtt](amqtt.md): Autonomous MQTT broker - [amqtt](amqtt.md): Autonomous MQTT broker
## Programming API ## Programming API
* [mqttclient](mqttclient.md): MQTT client API reference - [mqttclient](mqttclient.md): MQTT client API reference
* [broker](broker.md): MQTT broker API reference - [broker](broker.md): MQTT broker API reference
* [common](common.md): Common API - [common](common.md): Common API

1
docs/security.md 100644
Wyświetl plik

@ -0,0 +1 @@
--8<-- "SECURITY.md"

Wyświetl plik

@ -14,7 +14,7 @@ validation:
unrecognized_links: warn unrecognized_links: warn
nav: nav:
- Home: - Home:
- Overview: index.md - Overview: index.md
- Quickstart: quickstart.md - Quickstart: quickstart.md
- CLI Usage: - CLI Usage:
@ -24,6 +24,11 @@ nav:
- API Usage: - API Usage:
- Broker: references/broker.md - Broker: references/broker.md
- Client: references/client.md - Client: references/client.md
- Reference:
- Contributing: contributing.md
- Code of Conduct: code_of_conduct.md
- Security: security.md
- License: license.md
# - Changelog: changelog.md # - Changelog: changelog.md
# - Credits: credits.md # - Credits: credits.md
# - License: license.md # - License: license.md
@ -75,7 +80,6 @@ theme:
- search.suggest - search.suggest
- toc.follow - toc.follow
palette: palette:
# Palette toggle for light mode # Palette toggle for light mode
- scheme: default - scheme: default
toggle: toggle:
@ -99,50 +103,50 @@ extra_css:
#- js/feedback.js #- js/feedback.js
markdown_extensions: markdown_extensions:
- attr_list - attr_list
- admonition - admonition
- callouts: - callouts:
strip_period: false strip_period: false
- footnotes - footnotes
- pymdownx.details - pymdownx.details
- pymdownx.emoji: - pymdownx.emoji:
emoji_index: !!python/name:material.extensions.emoji.twemoji emoji_index: !!python/name:material.extensions.emoji.twemoji
emoji_generator: !!python/name:material.extensions.emoji.to_svg emoji_generator: !!python/name:material.extensions.emoji.to_svg
- pymdownx.highlight: - pymdownx.highlight:
pygments_lang_class: true pygments_lang_class: true
- pymdownx.magiclink - pymdownx.magiclink
- pymdownx.snippets: - pymdownx.snippets:
base_path: !relative $config_dir base_path: !relative $config_dir
check_paths: true check_paths: true
- pymdownx.superfences - pymdownx.superfences
- pymdownx.tabbed: - pymdownx.tabbed:
alternate_style: true alternate_style: true
slugify: !!python/object/apply:pymdownx.slugs.slugify slugify: !!python/object/apply:pymdownx.slugs.slugify
kwds: kwds:
case: lower case: lower
- pymdownx.tasklist: - pymdownx.tasklist:
custom_checkbox: true custom_checkbox: true
- pymdownx.tilde - pymdownx.tilde
- toc: - toc:
permalink: "¤" permalink: "¤"
plugins: plugins:
- search - search
- autorefs - autorefs
- markdown-exec - markdown-exec
- section-index - section-index
- coverage - coverage
- mkdocstrings: - mkdocstrings:
handlers: handlers:
python: python:
# inventories: # inventories:
# - https://docs.python.org/3/objects.inv # - https://docs.python.org/3/objects.inv
# - https://installer.readthedocs.io/en/stable/objects.inv # demonstration purpose in the docs # - https://installer.readthedocs.io/en/stable/objects.inv # demonstration purpose in the docs
# - https://mkdocstrings.github.io/autorefs/objects.inv # - https://mkdocstrings.github.io/autorefs/objects.inv
# - https://www.mkdocs.org/objects.inv # - https://www.mkdocs.org/objects.inv
# - https://python-markdown.github.io/objects.inv # - https://python-markdown.github.io/objects.inv
# - https://jinja.palletsprojects.com/en/stable/objects.inv # - https://jinja.palletsprojects.com/en/stable/objects.inv
# - https://markupsafe.palletsprojects.com/en/stable/objects.inv # - https://markupsafe.palletsprojects.com/en/stable/objects.inv
paths: [amqtt] paths: [amqtt]
options: options:
docstring_options: docstring_options:
@ -162,36 +166,36 @@ plugins:
show_symbol_type_toc: true show_symbol_type_toc: true
signature_crossrefs: true signature_crossrefs: true
summary: true summary: true
#- llmstxt: #- llmstxt:
# files: # files:
# - output: llms-full.txt # - output: llms-full.txt
# inputs: # inputs:
# - index.md # - index.md
# - usage/index.md # - usage/index.md
# - usage/handlers.md # - usage/handlers.md
# - usage/theming.md # - usage/theming.md
# - recipes.md # - recipes.md
# - troubleshooting.md # - troubleshooting.md
# - reference/**.md # - reference/**.md
- git-revision-date-localized: - git-revision-date-localized:
enabled: !ENV [DEPLOY, false] enabled: !ENV [DEPLOY, false]
enable_creation_date: true enable_creation_date: true
type: timeago type: timeago
#- redirects: #- redirects:
# redirect_maps: # redirect_maps:
# theming.md: usage/theming.md # theming.md: usage/theming.md
# handlers/overview.md: usage/handlers.md # handlers/overview.md: usage/handlers.md
# reference/index.md: reference/mkdocstrings.md#mkdocstrings # reference/index.md: reference/mkdocstrings.md#mkdocstrings
# reference/extension.md: reference/mkdocstrings.md#mkdocstrings.extension # reference/extension.md: reference/mkdocstrings.md#mkdocstrings.extension
# reference/handlers/index.md: reference/mkdocstrings.md#mkdocstrings.handlers # reference/handlers/index.md: reference/mkdocstrings.md#mkdocstrings.handlers
# reference/handlers/base.md: reference/mkdocstrings.md#mkdocstrings.handlers.base # reference/handlers/base.md: reference/mkdocstrings.md#mkdocstrings.handlers.base
# reference/handlers/rendering.md: reference/mkdocstrings.md#mkdocstrings.handlers.rendering # reference/handlers/rendering.md: reference/mkdocstrings.md#mkdocstrings.handlers.rendering
# reference/inventory.md: reference/mkdocstrings.md#mkdocstrings.inventory # reference/inventory.md: reference/mkdocstrings.md#mkdocstrings.inventory
# reference/loggers.md: reference/mkdocstrings.md#mkdocstrings.loggers # reference/loggers.md: reference/mkdocstrings.md#mkdocstrings.loggers
# reference/plugin.md: reference/mkdocstrings.md#mkdocstrings.plugin # reference/plugin.md: reference/mkdocstrings.md#mkdocstrings.plugin
- minify: - minify:
minify_html: !ENV [DEPLOY, false] minify_html: !ENV [DEPLOY, false]
- group: - group:
enabled: !ENV [MATERIAL_INSIDERS, false] enabled: !ENV [MATERIAL_INSIDERS, false]
plugins: plugins:
- typeset - typeset