Nicht nur für Hausautomatisierunge-Projekte, ein kleiner zentraler MQTT-Broker ist ein gutes Tool, um Sensordaten zu sammeln und an Steuerungsapplikationen weiterzuleiten. MQTT ist für solche Aufgaben gut geeignet, da es sich um ein leichtgewichtiges Protokoll handelt, was spezifisch für Sensorapplikationen entwickelt wurde. Daher funktioniert es auch sehr gut “nebenbei” auf einem Raspberry Pi.
Es gibt verschiedene MQTT-Implementationen. Sehr einfach lässt sich auf dem Raspberry Pi unter Raspbian Mosquitto nutzen. Die Installation ist sehr einfach:
sudo apt-get install -y mosquitto mosquitto-clients
Nun sollte der Moquitto-Server bereits laufen. Das kann wie folgt einfach getestet werden:
mosquitto_sub -h localhost -v -t test
Mit diesem Befehl wird ein MQTT Subscriber gestartet, der auf Nachrichten im “Test”-Kanal wartet.
Jetzt kann man eine zweite Verbindung zum Raspberry Pi starten und eine Nachricht absetzen:
mosquitto_pub -h localhost -t test -m "Hello world, Mosquitto"
Jetzt sollte der Subscriber die Nachricht “Hello world, Mosquitto” auf dem Bildschirm anzeigen.
Passwort einrichten
sudo stop mosquitto or sudo systemctl stop mosquitto.service
3. Creating the new password file
Password file will contain your username and the encrypted password. Run the following command to create and add a user to this file.
sudo mosquitto_passwd -c /etc/mosquitto/passwd <user_name>
Then, you will be asked for your password twice, enter that too.
4. Now we have to give the location of the password file to the Mosquitto broker config file. To do that open the mosquitto.conf file using the following command,
sudo nano /etc/mosquitto/mosquitto.conf
And add following two entries to the mosquitto.conf file,
password_file /etc/mosquitto/passwd allow_anonymous false
- “allow_anonymous false” is used to prevent, clients without username and password to connecting to the broker.
5. Now start the broker with the following command,
mosquitto -c /etc/mosquitto/mosquitto.conf or sudo systemctl start mosquitto.service
6. If you need to verify the authentication, you can use following command, (you have to install mosquitto clients to do this)
mosquitto_sub -h localhost -p 1883 -t myTopic -u <user_name> -P <password> or to show every message
mosquitto_sub -v -V mqttv311 -u <user_name> -P <password> -t "#"