/mosquitto-python-example

MQTT example using Mosquitto and Python

Primary LanguagePythonMIT LicenseMIT

Minor example using MQTT and Python. forked project

Requirements

Plan A. (not recommended)

Using test server: https://test.mosquitto.org/

Plan B is the new A

Requires Mosquitto to be installed.

On Linux/Ubuntu with the apt-get package manager:

apt update
apt install mosquitto
apt install mosquitto-clients

o:

apt install mosquitto mosquitto-clients

On /etc/mosquitto/mosquito.conf

# comment all lines and put these
listener 1883 0.0.0.0
allow_anonymous true

Launch the service

mkdir /run/mosquitto
chown mosquitto: /run/mosquitto/
# Testing
mosquitto -c /etc/mosquitto/mosquitto.conf -v

# Port in use?
ps -ef | grep mosquitto
kill <pid_proces>

#finally
service mosquitto start
service mosquitto status

Setup

Simply clone this repo, setup virtualenv and use pip to install requirements.

git clone https://github.com/wisaaco/mosquitto-python-example
cd mqtt-mosquitto-example
pip install -r requirements.txt

Modify the next line of subscriber.py:

client.connect("127.0.0.1", 1883, 60)

Test the subscriber example

Start the subscriber which will enter a loop waiting for new messages:

python3 subscriber.py

(Only with PlanB) Then open a new terminal and send a message:

mosquitto_pub -d -h localhost -q 0 -t perros/pics -m "Bonito cachorrito de perro maltes"

This should generate a message in the terminal running the subscriber.

Take a look at publisher.py to see how to publish messages using python. Or just open another terminal and run it from command line while subscriber.py is running:

python3 publisher.py

References