gmqtt

Python MQTT v5.0 async client

https://github.com/wialon/gmqtt

Science Score: 13.0%

This score indicates how likely this project is to be science-related based on various indicators:

  • CITATION.cff file
  • codemeta.json file
    Found codemeta.json file
  • .zenodo.json file
  • DOI references
  • Academic publication links
  • Committers with academic emails
  • Institutional organization owner
  • JOSS paper metadata
  • Scientific vocabulary similarity
    Low similarity (11.4%) to scientific vocabulary

Keywords

async asyncio mqtt mqttv5 python python-mqtt python-mqtt-client
Last synced: 6 months ago · JSON representation

Repository

Python MQTT v5.0 async client

Basic Info
  • Host: GitHub
  • Owner: wialon
  • License: mit
  • Language: Python
  • Default Branch: master
  • Homepage:
  • Size: 596 KB
Statistics
  • Stars: 427
  • Watchers: 20
  • Forks: 53
  • Open Issues: 28
  • Releases: 23
Topics
async asyncio mqtt mqttv5 python python-mqtt python-mqtt-client
Created about 8 years ago · Last pushed about 1 year ago
Metadata Files
Readme License

README.md

PyPI version build status Python versions codecov

gmqtt: Python async MQTT client implementation.

Installation

The latest stable version is available in the Python Package Index (PyPi) and can be installed using bash pip3 install gmqtt

Usage

Getting Started

Here is a very simple example that subscribes to the broker TOPIC topic and prints out the resulting messages:

```python import asyncio import os import signal import time

from gmqtt import Client as MQTTClient

gmqtt also compatibility with uvloop

import uvloop asyncio.seteventloop_policy(uvloop.EventLoopPolicy())

STOP = asyncio.Event()

def on_connect(client, flags, rc, properties): print('Connected') client.subscribe('TEST/#', qos=0)

def on_message(client, topic, payload, qos, properties): print('RECV MSG:', payload)

def on_disconnect(client, packet, exc=None): print('Disconnected')

def on_subscribe(client, mid, qos, properties): print('SUBSCRIBED')

def ask_exit(*args): STOP.set()

async def main(broker_host, token): client = MQTTClient("client-id")

client.on_connect = on_connect
client.on_message = on_message
client.on_disconnect = on_disconnect
client.on_subscribe = on_subscribe

client.set_auth_credentials(token, None)
await client.connect(broker_host)

client.publish('TEST/TIME', str(time.time()), qos=1)

await STOP.wait()
await client.disconnect()

if name == 'main': loop = asyncio.geteventloop()

host = 'mqtt.flespi.io'
token = os.environ.get('FLESPI_TOKEN')

loop.add_signal_handler(signal.SIGINT, ask_exit)
loop.add_signal_handler(signal.SIGTERM, ask_exit)

loop.run_until_complete(main(host, token))

```

MQTT Version 5.0

gmqtt supports MQTT version 5.0 protocol

Version setup

Version 5.0 is used by default. If your broker does not support 5.0 protocol version and responds with proper CONNACK reason code, client will downgrade to 3.1 and reconnect automatically. Note, that some brokers just fail to parse the 5.0 format CONNECT packet, so first check manually if your broker handles this properly. You can also force version in connect method: python from gmqtt.mqtt.constants import MQTTv311 client = MQTTClient('clientid') client.set_auth_credentials(token, None) await client.connect(broker_host, 1883, keepalive=60, version=MQTTv311)

Properties

MQTT 5.0 protocol allows to include custom properties into packages, here is example of passing response topic property in published message: ```python

TOPIC = 'testtopic/TOPIC'

def on_connect(client, flags, rc, properties): client.subscribe(TOPIC, qos=1) print('Connected')

def on_message(client, topic, payload, qos, properties): print('RECV MSG:', topic, payload.decode(), properties)

async def main(brokerhost, token): client = MQTTClient('asdfghjk') client.onmessage = onmessage client.onconnect = onconnect client.setauthcredentials(token, None) await client.connect(brokerhost, 1883, keepalive=60) client.publish(TOPIC, 'Message payload', response_topic='RESPONSE/TOPIC')

await STOP.wait()
await client.disconnect()

```

Connect properties

Connect properties are passed to Client object as kwargs (later they are stored together with properties received from broker in client.properties field). See example below. * session_expiry_interval - int Session expiry interval in seconds. If the Session Expiry Interval is absent the value 0 is used. If it is set to 0, or is absent, the Session ends when the Network Connection is closed. If the Session Expiry Interval is 0xFFFFFFFF (max possible value), the Session does not expire. * receive_maximum - int The Client uses this value to limit the number of QoS 1 and QoS 2 publications that it is willing to process concurrently. * user_property - tuple(str, str) This property may be used to provide additional diagnostic or other information (key-value pairs). * maximum_packet_size - int The Client uses the Maximum Packet Size (in bytes) to inform the Server that it will not process packets exceeding this limit.

Example: python client = gmqtt.Client("lenkaklient", receive_maximum=24000, session_expiry_interval=60, user_property=('myid', '12345'))

Publish properties

This properties will be also sent in publish packet from broker, they will be passed to on_message callback. * message_expiry_interval - int If present, the value is the lifetime of the Application Message in seconds. * content_type - unicode UTF-8 Encoded String describing the content of the Application Message. The value of the Content Type is defined by the sending and receiving application. * user_property - tuple(str, str) * subscription_identifier - int (see subscribe properties) sent by broker * topic_alias - int First client publishes messages with topic string and kwarg topicalias. After this initial message client can publish message with empty string topic and same topicalias kwarg.

Example: ```python def onmessage(client, topic, payload, qos, properties): # properties example here: {'contenttype': ['json'], 'userproperty': [('timestamp', '1524235334.881058')], 'messageexpiryinterval': [60], 'subscriptionidentifier': [42, 64]} print('RECV MSG:', topic, payload, properties)

client.publish('TEST/TIME', str(time.time()), qos=1, retain=True, messageexpiryinterval=60, content_type='json') ```

Subscribe properties
  • subscription_identifier - int If the Client specified a Subscription Identifier for any of the overlapping subscriptions the Server MUST send those Subscription Identifiers in the message which is published as the result of the subscriptions.

Reconnects

By default, connected MQTT client will always try to reconnect in case of lost connections. Number of reconnect attempts is unlimited. If you want to change this behaviour, do the following: python client = MQTTClient("client-id") client.set_config({'reconnect_retries': 10, 'reconnect_delay': 60}) Code above will set number of reconnect attempts to 10 and delay between reconnect attempts to 1min (60s). By default reconnect_delay=6 and reconnect_retries=-1 which stands for infinity. Note that manually calling await client.disconnect() will set reconnect_retries for 0, which will stop auto reconnect.

Asynchronous on_message callback

You can define asynchronous onmessage callback. Note that it must return valid PUBACK code (0 is success code, see full list in constants) ```python async def onmessage(client, topic, payload, qos, properties): pass return 0 ```

Other examples

Check examples directory for more use cases.

Owner

  • Name: Gurtam
  • Login: wialon
  • Kind: user
  • Location: Vilnius, Lithuania, EU
  • Company: Gurtam

GitHub Events

Total
  • Create event: 1
  • Issues event: 2
  • Release event: 1
  • Watch event: 26
  • Issue comment event: 1
  • Push event: 2
  • Pull request event: 2
  • Fork event: 2
Last Year
  • Create event: 1
  • Issues event: 2
  • Release event: 1
  • Watch event: 26
  • Issue comment event: 1
  • Push event: 2
  • Pull request event: 2
  • Fork event: 2

Committers

Last synced: 9 months ago

All Time
  • Total Commits: 125
  • Total Committers: 19
  • Avg Commits per committer: 6.579
  • Development Distribution Score (DDS): 0.632
Past Year
  • Commits: 2
  • Committers: 1
  • Avg Commits per committer: 2.0
  • Development Distribution Score (DDS): 0.0
Top Committers
Name Email Commits
Lenka42 e****o@g****m 46
Elena Shylko n****l@g****m 27
mitu m****u@g****m 22
Gurtam d****t@g****m 7
Oleg Chirich c****l@g****m 5
Fabian Affolter m****l@f****h 5
Dirk Faust d****f@c****m 1
Garkavyj, Vladimir v****j@w****m 1
Arseny Kirichenko m****6@g****m 1
Giovanni Condello n****d 1
Guillaume Desvé g****z@g****m 1
Jesús García Sáez b****r@g****m 1
Kevron Rees t****v@g****m 1
Mike Turchunovich M****y@g****m 1
Moritz Laass m****s@g****m 1
René Krell r****l@g****m 1
YCC_0x0CA s****g@g****m 1
space-gurtam 4****m 1
xiaoliuhust x****t@g****m 1
Committer Domains (Top 20 + Academic)

Issues and Pull Requests

Last synced: 7 months ago

All Time
  • Total issues: 69
  • Total pull requests: 44
  • Average time to close issues: 18 days
  • Average time to close pull requests: 2 days
  • Total issue authors: 54
  • Total pull request authors: 19
  • Average comments per issue: 3.32
  • Average comments per pull request: 0.93
  • Merged pull requests: 37
  • Bot issues: 0
  • Bot pull requests: 0
Past Year
  • Issues: 1
  • Pull requests: 2
  • Average time to close issues: 7 minutes
  • Average time to close pull requests: N/A
  • Issue authors: 1
  • Pull request authors: 2
  • Average comments per issue: 1.0
  • Average comments per pull request: 0.0
  • Merged pull requests: 0
  • Bot issues: 0
  • Bot pull requests: 0
Top Authors
Issue Authors
  • nicola-lunghi (3)
  • Allineer (3)
  • Yingliangzhe (2)
  • naquad (2)
  • fabaff (2)
  • DurandA (2)
  • HerrMuellerluedenscheid (2)
  • canique (2)
  • stefangotz (2)
  • hollymcr (2)
  • honglei (2)
  • jeffreykira (2)
  • cloud-rocket (2)
  • KeNaCo (1)
  • Shraddha-gami-source (1)
Pull Request Authors
  • Lenka42 (22)
  • fabaff (4)
  • saurabhritu (2)
  • KeNaCo (2)
  • nanomad (2)
  • blaxter (1)
  • sunnyanthony (1)
  • ukalwa (1)
  • gdraynz (1)
  • xiaoliuhust (1)
  • space-gurtam (1)
  • Dirk007 (1)
  • YraganTron (1)
  • rkrell (1)
  • gstein (1)
Top Labels
Issue Labels
Pull Request Labels

Packages

  • Total packages: 2
  • Total downloads:
    • pypi 53,176 last-month
  • Total docker downloads: 990
  • Total dependent packages: 18
    (may contain duplicates)
  • Total dependent repositories: 63
    (may contain duplicates)
  • Total versions: 89
  • Total maintainers: 1
pypi.org: gmqtt

Client for MQTT protocol

  • Versions: 67
  • Dependent Packages: 18
  • Dependent Repositories: 63
  • Downloads: 53,176 Last month
  • Docker Downloads: 990
Rankings
Dependent packages count: 0.7%
Docker downloads count: 1.6%
Dependent repos count: 1.9%
Downloads: 2.2%
Average: 2.6%
Stargazers count: 3.4%
Forks count: 5.8%
Maintainers (1)
Last synced: 6 months ago
proxy.golang.org: github.com/wialon/gmqtt
  • Versions: 22
  • Dependent Packages: 0
  • Dependent Repositories: 0
Rankings
Dependent packages count: 6.5%
Average: 6.7%
Dependent repos count: 6.9%
Last synced: 6 months ago

Dependencies

.github/workflows/python-package.yml actions
  • actions/checkout v3 composite
  • actions/setup-python v3 composite
requirements_test.txt pypi
setup.py pypi