-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathREADME.md
233 lines (169 loc) · 6.4 KB
/
README.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# 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.
[![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)
[![Anaconda-Server Badge](https://anaconda.org/conda-forge/flask-mqtt/badges/installer/conda.svg)](https://conda.anaconda.org/conda-forge)
[![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/