Flask-MQTT


NameFlask-MQTT JSON
Version 1.2.1 PyPI version JSON
download
home_pagehttps://github.com/MrLeeh/Flask-MQTT
SummaryFlask extension for the MQTT protocol
upload_time2024-03-15 22:51:40
maintainer
docs_urlNone
authorStefan Lehmann
requires_python>=3.6
licenseMIT
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Flask-MQTT

Flask Extension for the [MQTT protocol][1]. Basically it is a thin wrapper
around [paho-mqtt][0] and aims to simplify MQTT integration in Flask. MQTT is a
machine-to-machine "Internet of Things" protocol and was designed for extremely
lightweight publish/subscribe messaging transport.

[![Inactively Maintained](https://img.shields.io/badge/Maintenance%20Level-Inactively%20Maintained-yellowgreen.svg)](https://gist.github.com/cheerfulstoic/d107229326a01ff0f333a1d3476e068d)
[![Documentation Status](https://readthedocs.org/projects/flask-mqtt/badge/?version=latest)](http://flask-mqtt.readthedocs.io/en/latest/?badge=latest)
[![PyPI version](https://badge.fury.io/py/Flask-MQTT.svg)](https://badge.fury.io/py/Flask-MQTT)
[![CI](https://github.com/stlehmann/Flask-MQTT/actions/workflows/ci.yml/badge.svg)](https://github.com/stlehmann/Flask-MQTT/actions/workflows/ci.yml)
[![Coverage Status](https://coveralls.io/repos/github/stlehmann/Flask-MQTT/badge.svg?branch=master)](https://coveralls.io/github/stlehmann/Flask-MQTT?branch=master)
[![Downloads](https://pepy.tech/badge/flask-mqtt)](https://pepy.tech/project/flask-mqtt)
[![Downloads](https://pepy.tech/badge/flask-mqtt/week)](https://pepy.tech/project/flask-mqtt/week)

Find the documentation on [http://flask-mqtt.readthedocs.io][2].

## Features

* configuration via Flask config variables
* auto-connect on start of your web application
* publish and subscribe messages
* connect to multiple MQTT servers
* use callbacks for certain topics
* use one callback for all subscribed topics

## Limitations

Flask-MQTT was developed to provide an easy-to-setup solution for interacting
with IoT devices. A typical scenario would be a Raspberry Pi running a
mosquitto mqtt server combined with a Flask webserver.

### Multiple workers

**Flask-MQTT is currently not suitable for the use with multiple worker
instances.** So if you use a WSGI server like *gevent* or *gunicorn* make sure
you only have one worker instance.

### Reloader

Make sure to disable Flasks autoreloader. If activated it spawns two
instances of a Flask application. This leads to the same problems as multiple
workers. To prevent Flask-MQTT from running code twice it is necessary to
deactivate the automatic reloader.

## Installation

Simply install the package as usual via pip:

```bash
$ pip install flask-mqtt
```

Or with conda from the conda-forge channel:

```bash
$ conda config --add channels conda-forge
$ conda install flask-mqtt
```

## Usage

### Basic Setup

```python
from flask import Flask
from flask_mqtt import Mqtt

app = Flask(__name__)
app.config['MQTT_BROKER_URL'] = 'mybroker.com'
app.config['MQTT_BROKER_PORT'] = 1883
app.config['MQTT_USERNAME'] = 'user'
app.config['MQTT_PASSWORD'] = 'secret'
app.config['MQTT_REFRESH_TIME'] = 1.0  # refresh time in seconds
mqtt = Mqtt(app)

@app.route('/')
def index():
    return render_template('index.html')

```

### Subscribe to a topic

To subscribe to a topic simply use `mqtt.subscribe()`. To make sure the
subscription gets handled correctly on startup place the subscription inside
an `on_connect()` callback function.

```python
@mqtt.on_connect()
def handle_connect(client, userdata, flags, rc):
    mqtt.subscribe('home/mytopic')
```

To handle the subscribed messages you can define a handling function by
decorating it with `@mqtt.on_message()`.

```python
@mqtt.on_message()
def handle_mqtt_message(client, userdata, message):
    data = dict(
        topic=message.topic,
        payload=message.payload.decode()
    )
```

To unsubscribe do:

```python
mqtt.unsubscribe('home/mytopic')
```

Or if you want to unsubscribe all topics use `unsubscribe_all()`.

```python
mqtt.unsubscribe_all()
```

### Publish

To publish a message you can use the `publish()` method.

```python
mqtt.publish('home/mytopic', 'this is my message')
```

### Connect to multiple MQTT Servers

To connect to multiple servers, you can create multiple mqtt clients in your application by specifying the ```config_prefix``` when initializing ```Mqtt()```

```python
# default mqtt client
app.config["MQTT_broker_url"] = "example.com"
app.config["MQTT_broker_port"] = 8883
mqtt = Mqtt(app)

# create second mqtt client for a different broker 
app.config["MQTT2_broker_url"] = "example2.com"
app.config["MQTT_broker_port"] = 1883
mqtt2 = Mqtt(app, config_prefix="MQTT2")

# create third mqtt client for a different broker 
app.config["MQTT3_broker_url"] = "example3.com"
app.config["MQTT3_broker_port"] = 1885
mqtt3 = Mqtt(app, config_prefix="MQTT3")
```

### Small publish/subscribe MQTT client

```python
"""

A small Test application to show how to use Flask-MQTT.

"""

import eventlet
import json
from flask import Flask, render_template
from flask_mqtt import Mqtt
from flask_socketio import SocketIO
from flask_bootstrap import Bootstrap

eventlet.monkey_patch()

app = Flask(__name__)
app.config['SECRET'] = 'my secret key'
app.config['TEMPLATES_AUTO_RELOAD'] = True
app.config['MQTT_BROKER_URL'] = 'broker.hivemq.com'
app.config['MQTT_BROKER_PORT'] = 1883
app.config['MQTT_USERNAME'] = ''
app.config['MQTT_PASSWORD'] = ''
app.config['MQTT_KEEPALIVE'] = 5
app.config['MQTT_TLS_ENABLED'] = False
app.config['MQTT_CLEAN_SESSION'] = True

# Parameters for SSL enabled
# app.config['MQTT_BROKER_PORT'] = 8883
# app.config['MQTT_TLS_ENABLED'] = True
# app.config['MQTT_TLS_INSECURE'] = True
# app.config['MQTT_TLS_CA_CERTS'] = 'ca.crt'

mqtt = Mqtt(app)
socketio = SocketIO(app)
bootstrap = Bootstrap(app)


@app.route('/')
def index():
    return render_template('index.html')


@socketio.on('publish')
def handle_publish(json_str):
    data = json.loads(json_str)
    mqtt.publish(data['topic'], data['message'])


@socketio.on('subscribe')
def handle_subscribe(json_str):
    data = json.loads(json_str)
    mqtt.subscribe(data['topic'])


@socketio.on('unsubscribe_all')
def handle_unsubscribe_all():
    mqtt.unsubscribe_all()


@mqtt.on_message()
def handle_mqtt_message(client, userdata, message):
    data = dict(
        topic=message.topic,
        payload=message.payload.decode()
    )
    socketio.emit('mqtt_message', data=data)


@mqtt.on_log()
def handle_logging(client, userdata, level, buf):
    print(level, buf)


if __name__ == '__main__':
    # important: Do not use reloader because this will create two Flask instances.
    # Flask-MQTT only supports running with one instance
    socketio.run(app, host='0.0.0.0', port=5000, use_reloader=False, debug=False)

```

[0]: https://github.com/eclipse/paho.mqtt.python
[1]: http://mqtt.org/
[2]: http://flask-mqtt.readthedocs.io/en/latest/

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/MrLeeh/Flask-MQTT",
    "name": "Flask-MQTT",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.6",
    "maintainer_email": "",
    "keywords": "",
    "author": "Stefan Lehmann",
    "author_email": "stefan.st.lehmann@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/cb/d1/5cbf49abad77fc6d943d8402e4e18fe249225526c576b36996ec3492f9e5/Flask-MQTT-1.2.1.tar.gz",
    "platform": "any",
    "description": "# Flask-MQTT\r\n\r\nFlask Extension for the [MQTT protocol][1]. Basically it is a thin wrapper\r\naround [paho-mqtt][0] and aims to simplify MQTT integration in Flask. MQTT is a\r\nmachine-to-machine \"Internet of Things\" protocol and was designed for extremely\r\nlightweight publish/subscribe messaging transport.\r\n\r\n[![Inactively Maintained](https://img.shields.io/badge/Maintenance%20Level-Inactively%20Maintained-yellowgreen.svg)](https://gist.github.com/cheerfulstoic/d107229326a01ff0f333a1d3476e068d)\r\n[![Documentation Status](https://readthedocs.org/projects/flask-mqtt/badge/?version=latest)](http://flask-mqtt.readthedocs.io/en/latest/?badge=latest)\r\n[![PyPI version](https://badge.fury.io/py/Flask-MQTT.svg)](https://badge.fury.io/py/Flask-MQTT)\r\n[![CI](https://github.com/stlehmann/Flask-MQTT/actions/workflows/ci.yml/badge.svg)](https://github.com/stlehmann/Flask-MQTT/actions/workflows/ci.yml)\r\n[![Coverage Status](https://coveralls.io/repos/github/stlehmann/Flask-MQTT/badge.svg?branch=master)](https://coveralls.io/github/stlehmann/Flask-MQTT?branch=master)\r\n[![Downloads](https://pepy.tech/badge/flask-mqtt)](https://pepy.tech/project/flask-mqtt)\r\n[![Downloads](https://pepy.tech/badge/flask-mqtt/week)](https://pepy.tech/project/flask-mqtt/week)\r\n\r\nFind the documentation on [http://flask-mqtt.readthedocs.io][2].\r\n\r\n## Features\r\n\r\n* configuration via Flask config variables\r\n* auto-connect on start of your web application\r\n* publish and subscribe messages\r\n* connect to multiple MQTT servers\r\n* use callbacks for certain topics\r\n* use one callback for all subscribed topics\r\n\r\n## Limitations\r\n\r\nFlask-MQTT was developed to provide an easy-to-setup solution for interacting\r\nwith IoT devices. A typical scenario would be a Raspberry Pi running a\r\nmosquitto mqtt server combined with a Flask webserver.\r\n\r\n### Multiple workers\r\n\r\n**Flask-MQTT is currently not suitable for the use with multiple worker\r\ninstances.** So if you use a WSGI server like *gevent* or *gunicorn* make sure\r\nyou only have one worker instance.\r\n\r\n### Reloader\r\n\r\nMake sure to disable Flasks autoreloader. If activated it spawns two\r\ninstances of a Flask application. This leads to the same problems as multiple\r\nworkers. To prevent Flask-MQTT from running code twice it is necessary to\r\ndeactivate the automatic reloader.\r\n\r\n## Installation\r\n\r\nSimply install the package as usual via pip:\r\n\r\n```bash\r\n$ pip install flask-mqtt\r\n```\r\n\r\nOr with conda from the conda-forge channel:\r\n\r\n```bash\r\n$ conda config --add channels conda-forge\r\n$ conda install flask-mqtt\r\n```\r\n\r\n## Usage\r\n\r\n### Basic Setup\r\n\r\n```python\r\nfrom flask import Flask\r\nfrom flask_mqtt import Mqtt\r\n\r\napp = Flask(__name__)\r\napp.config['MQTT_BROKER_URL'] = 'mybroker.com'\r\napp.config['MQTT_BROKER_PORT'] = 1883\r\napp.config['MQTT_USERNAME'] = 'user'\r\napp.config['MQTT_PASSWORD'] = 'secret'\r\napp.config['MQTT_REFRESH_TIME'] = 1.0  # refresh time in seconds\r\nmqtt = Mqtt(app)\r\n\r\n@app.route('/')\r\ndef index():\r\n    return render_template('index.html')\r\n\r\n```\r\n\r\n### Subscribe to a topic\r\n\r\nTo subscribe to a topic simply use `mqtt.subscribe()`. To make sure the\r\nsubscription gets handled correctly on startup place the subscription inside\r\nan `on_connect()` callback function.\r\n\r\n```python\r\n@mqtt.on_connect()\r\ndef handle_connect(client, userdata, flags, rc):\r\n    mqtt.subscribe('home/mytopic')\r\n```\r\n\r\nTo handle the subscribed messages you can define a handling function by\r\ndecorating it with `@mqtt.on_message()`.\r\n\r\n```python\r\n@mqtt.on_message()\r\ndef handle_mqtt_message(client, userdata, message):\r\n    data = dict(\r\n        topic=message.topic,\r\n        payload=message.payload.decode()\r\n    )\r\n```\r\n\r\nTo unsubscribe do:\r\n\r\n```python\r\nmqtt.unsubscribe('home/mytopic')\r\n```\r\n\r\nOr if you want to unsubscribe all topics use `unsubscribe_all()`.\r\n\r\n```python\r\nmqtt.unsubscribe_all()\r\n```\r\n\r\n### Publish\r\n\r\nTo publish a message you can use the `publish()` method.\r\n\r\n```python\r\nmqtt.publish('home/mytopic', 'this is my message')\r\n```\r\n\r\n### Connect to multiple MQTT Servers\r\n\r\nTo connect to multiple servers, you can create multiple mqtt clients in your application by specifying the ```config_prefix``` when initializing ```Mqtt()```\r\n\r\n```python\r\n# default mqtt client\r\napp.config[\"MQTT_broker_url\"] = \"example.com\"\r\napp.config[\"MQTT_broker_port\"] = 8883\r\nmqtt = Mqtt(app)\r\n\r\n# create second mqtt client for a different broker \r\napp.config[\"MQTT2_broker_url\"] = \"example2.com\"\r\napp.config[\"MQTT_broker_port\"] = 1883\r\nmqtt2 = Mqtt(app, config_prefix=\"MQTT2\")\r\n\r\n# create third mqtt client for a different broker \r\napp.config[\"MQTT3_broker_url\"] = \"example3.com\"\r\napp.config[\"MQTT3_broker_port\"] = 1885\r\nmqtt3 = Mqtt(app, config_prefix=\"MQTT3\")\r\n```\r\n\r\n### Small publish/subscribe MQTT client\r\n\r\n```python\r\n\"\"\"\r\n\r\nA small Test application to show how to use Flask-MQTT.\r\n\r\n\"\"\"\r\n\r\nimport eventlet\r\nimport json\r\nfrom flask import Flask, render_template\r\nfrom flask_mqtt import Mqtt\r\nfrom flask_socketio import SocketIO\r\nfrom flask_bootstrap import Bootstrap\r\n\r\neventlet.monkey_patch()\r\n\r\napp = Flask(__name__)\r\napp.config['SECRET'] = 'my secret key'\r\napp.config['TEMPLATES_AUTO_RELOAD'] = True\r\napp.config['MQTT_BROKER_URL'] = 'broker.hivemq.com'\r\napp.config['MQTT_BROKER_PORT'] = 1883\r\napp.config['MQTT_USERNAME'] = ''\r\napp.config['MQTT_PASSWORD'] = ''\r\napp.config['MQTT_KEEPALIVE'] = 5\r\napp.config['MQTT_TLS_ENABLED'] = False\r\napp.config['MQTT_CLEAN_SESSION'] = True\r\n\r\n# Parameters for SSL enabled\r\n# app.config['MQTT_BROKER_PORT'] = 8883\r\n# app.config['MQTT_TLS_ENABLED'] = True\r\n# app.config['MQTT_TLS_INSECURE'] = True\r\n# app.config['MQTT_TLS_CA_CERTS'] = 'ca.crt'\r\n\r\nmqtt = Mqtt(app)\r\nsocketio = SocketIO(app)\r\nbootstrap = Bootstrap(app)\r\n\r\n\r\n@app.route('/')\r\ndef index():\r\n    return render_template('index.html')\r\n\r\n\r\n@socketio.on('publish')\r\ndef handle_publish(json_str):\r\n    data = json.loads(json_str)\r\n    mqtt.publish(data['topic'], data['message'])\r\n\r\n\r\n@socketio.on('subscribe')\r\ndef handle_subscribe(json_str):\r\n    data = json.loads(json_str)\r\n    mqtt.subscribe(data['topic'])\r\n\r\n\r\n@socketio.on('unsubscribe_all')\r\ndef handle_unsubscribe_all():\r\n    mqtt.unsubscribe_all()\r\n\r\n\r\n@mqtt.on_message()\r\ndef handle_mqtt_message(client, userdata, message):\r\n    data = dict(\r\n        topic=message.topic,\r\n        payload=message.payload.decode()\r\n    )\r\n    socketio.emit('mqtt_message', data=data)\r\n\r\n\r\n@mqtt.on_log()\r\ndef handle_logging(client, userdata, level, buf):\r\n    print(level, buf)\r\n\r\n\r\nif __name__ == '__main__':\r\n    # important: Do not use reloader because this will create two Flask instances.\r\n    # Flask-MQTT only supports running with one instance\r\n    socketio.run(app, host='0.0.0.0', port=5000, use_reloader=False, debug=False)\r\n\r\n```\r\n\r\n[0]: https://github.com/eclipse/paho.mqtt.python\r\n[1]: http://mqtt.org/\r\n[2]: http://flask-mqtt.readthedocs.io/en/latest/\r\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Flask extension for the MQTT protocol",
    "version": "1.2.1",
    "project_urls": {
        "Homepage": "https://github.com/MrLeeh/Flask-MQTT"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "05ef9118543adfbcfa3cc4423aaf517e8ef8d038da55c4b7749e35464e3ea4b4",
                "md5": "4a65e7fe5e28922b8dd7fdbf3bad44ce",
                "sha256": "0a93ec45fc3176647e7e56d8d9047a51680a6c0fcb14b174aea6bacc161bbd06"
            },
            "downloads": -1,
            "filename": "Flask_MQTT-1.2.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "4a65e7fe5e28922b8dd7fdbf3bad44ce",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.6",
            "size": 9181,
            "upload_time": "2024-03-15T22:51:38",
            "upload_time_iso_8601": "2024-03-15T22:51:38.626955Z",
            "url": "https://files.pythonhosted.org/packages/05/ef/9118543adfbcfa3cc4423aaf517e8ef8d038da55c4b7749e35464e3ea4b4/Flask_MQTT-1.2.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "cbd15cbf49abad77fc6d943d8402e4e18fe249225526c576b36996ec3492f9e5",
                "md5": "74d722b1863d2fe26448b893614dc11c",
                "sha256": "48d0d44b16e6cb5309b9ebb1d62f1de80633852c426d97c86d348f67e4a65555"
            },
            "downloads": -1,
            "filename": "Flask-MQTT-1.2.1.tar.gz",
            "has_sig": false,
            "md5_digest": "74d722b1863d2fe26448b893614dc11c",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.6",
            "size": 12097,
            "upload_time": "2024-03-15T22:51:40",
            "upload_time_iso_8601": "2024-03-15T22:51:40.312093Z",
            "url": "https://files.pythonhosted.org/packages/cb/d1/5cbf49abad77fc6d943d8402e4e18fe249225526c576b36996ec3492f9e5/Flask-MQTT-1.2.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-03-15 22:51:40",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "MrLeeh",
    "github_project": "Flask-MQTT",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [],
    "lcname": "flask-mqtt"
}
        
Elapsed time: 9.01683s