HowTo: FHEM – Create MQTT devices

In the article RaspberryPi - Install MQTT Server on the RaspberryPi I had written a little about MQTT and explained how to install an own MQTT server on the RaspberryPi.

In order to be able to use an MQTT server from FHEM, you have to install a few FHEM modules. How to do that and what you have to pay attention to I have described in the following article.


Safety instructions

I know the following notes are always kind of annoying and seem unnecessary. Unfortunately, many people who knew "better" have lost eyes, fingers or other things due to carelessness or injured themselves. Data loss is almost negligible in comparison, but even these can be really annoying. Therefore, please take five minutes to read the safety instructions. Because even the coolest project is not worth injury or other trouble.
https://www.nerdiy.de/sicherheitshinweise/

Affiliate links/advertising links

The links to online shops listed here are so-called affiliate links. If you click on such an affiliate link and make a purchase via this link, Nerdiy.de will receive a commission from the relevant online shop or provider. The price does not change for you. If you make your purchases via these links, you support Nerdiy.de in being able to offer other useful projects in the future. 🙂 


Requirements

Before you start with this article you should have prepared the RaspberryPi so that it is accessible via the network and controllable via SSH.

The following three articles describe what needs to be done to prepare the RaspberryPi:
RaspberryPi – setup for nerdiys!
RaspberryPi – The first configuration!
RaspberryPi – Control the RaspberryPi via SSH
Your own smart home - installation and getting started with FHEM
Mosquitto on the Raspberry - Install MQTT Server on the RaspberryPi

Tools needed:
-no-

Materials needed:

In the following list you will find all the parts you need to implement this article.


Log in to the RaspberryPi via SSH

To start, you must first log in to the Rasp Pi with Putty via SSH. How to do this is in the article RaspberryPi - Control the RaspberryPi via SSH described.

After entering your username and password you can enter the first commands.

Update package management

The package management in Linux is a "central place" through which various software packages can be installed. In order for this to work reliably, the lists and sources of the package management should be updated before each installation of new packages.

To start the update of the package management you have to enter the following command.
sudo apt-get update && sudo apt-get upgrade
Depending on how long ago your last update of the package management was, this process can now take a while. The lists that refer to the individual package sources are updated first.
After that, the packages themselves are updated. Since additional memory is occupied, you will be asked again for your consent. You have to confirm this with a "J" and "Enter".
Once the update is complete, you will see a small summary of the duration and scope of the update.

Install Perl MQTT packages

In order for FHEM to communicate with the MQTT server, two Perl packages must be installed.

For this you have to log in with Putty on the RasPi and enter the following command.
sudo apt-get install libmodule-pluggable-perl && sudo cpan install Net::MQTT:Simple && sudo cpan install Net::MQTT:Constants
Die Warnung, dass dadurch zusätzlicher Speicherplatz belegt wird quittiert Ihr mit einem “J” und “Enter”.

Die Nachfrage “Would you like to configure as much as possible automatically? [yes]” bestaetigt ihr mit “yes” und Enter.
The installation of the two packages took me about five minutes. So time enough to get a new coffee 🙂 .


Create MQTT clients

In order to establish a connection with an MQTT device in the next step, an MQTT client must first be created. This will later save the necessary data for the connection with the MQTT server.

To do this, enter the following command in the command prompt of your FHEM instance.
define mqttClient MQTT 192.168.0.1:1883

Der Befehl zum erstellen eines MQTT-Clienten entspricht dabei der folgenden “define Name-des-mqtt-clienten MQTT host-oder-ip-des-mqtt-servers:port-des-servers”. Hat Euer MQTT-Server also die IP-Adresse “192.168.0.1”, den Port 1883 was dem Standardport für MQTT entspricht) so lautet der Befehl zum erstellen des MQTT-Clienten “define mqttClient MQTT 192.168.0.1:1883”. Dabei kann für “mqttClient” natürlich auch jeder andere beliebige Name verwendet werden.

Klickt nun oben links auf “Save config” und startet Euren FHEM-Server mithilfe des folgenden Befehls neu.
shutdown restart

After the server is restarted, you are ready to create new MQTT bridges and devices.

View of the newly created MQTT client. Here you can see if a connection to the MQTT server could be established. In addition, more information about the connection to the MQTT server is displayed.
Damit die gemachten Änderungen übernommen und dauerhaft gespeichert bleiben müsst Ihr unbedingt daran denken auf “Save config” zu klicken. Dadurch werden die geänderten Einstellungen dauerhaft in der Konfigurationsdatei gespeichert.

Setting up the MQTT Bridge using the example of a MAX! heating thermostat

In this example, we create an MQTT bridge. As the name suggests, the MQTT bridge connects something to each other. In this case the MAX! heating thermostat with the MQTT world. In principle, this link works according to the same scheme with all already installed sensors or actuators. In the case of the MAX! heating thermostat, this works with the following command.

Die Struktur des Befehls ist dabei wie folgt aufgebaut “define Name-der-mqtt-bridge MQTT_BRIDGE Name-des-sensors-bzw-aktors”. Im Fall des MAX! Heizungsthermostats mit dem Namen “MAX_15504f” lautet der Befehl also folgendermaßen.
defineHeatingWorkroomMqtt MQTT_BRIDGE MAX_15504f

Dadurch wird das Modul “HeizungArbeitszimmerMqtt” vom Typ “MQTT_BRIDGE” angelegt und mit dem bereits vorhandenen Modul “MAX_15504f” verknüpft.

Die erstellte MQTT_BRIDGE befindet sich nun im Raum “Unsorted”. Wechselt in diesen Raum und öffnet die Detailansicht der erstellten MQTT-Bridge.
In the detail view you can now see all information about the created MQTT bridge. However, before the MQTT bridge can connect data from the MAX! heating thermostat with the MQTT world, it must first know which reading of the heating thermostat is to be linked with which MQTT topic.

Dazu gibt es das Attribut “publishReading_XYZ”. Dieses bewirkt, dass die MQTT-Bridge alle Aktualisierungen auf dem Reading “XYZ” automatisch an das angegebene Topic weitergeleitet wird.

Gebt also folgenden Befehl in die Befehlseingabe Eurer FHEM-Instanz ein um automatisch jede aktualisierung des Readings “temperature” an das Topic “heizung/Arbeitszimmer/temperature” weiterleiten zu lassen.
attr HeizArbeitszimmerMqtt publishReading_temperature heizung/Arbeitszimmer/temperature

Achtet hierbei darauf, dass “publishReading” und “temperature”(das reading des Heizkörperthermostats(oder jedes anderen Sensors/Aktors)) mit einem Unterstrich verbunden sein müssen. So ergibt sich “publishReading_temperature”.
Für das Reading “Battery” würde das ganze dann folgendermaßen aussehen.

attr HeizArbeitszimmerMqtt publishReading_battery heizung/Arbeitszimmer/battery
This linking of reading and MQTT topics also works the other way around. So that values sent to an MQTT topic are automatically entered into a reading of the heating thermostat, you must set the following attribute.
attr HeizArbeitszimmerMqtt subscribeSet_desiredTemperature heizung/Arbeitszimmer/desiredTemperature

Dies bewirkt, dass das Topic “heizung/Arbeitszimmer/desiredTemperature” aboniert wird und jeder darauf eingehender Wert automatisch in das Reading “desiredTemperature” eingetragen wird. Auf diesem Wege könnt Ihr die gewünschte Temperatur des Heizungsthermostats per MQTT-Nachricht steuern.

Die Detailansicht Eurer MQTT-Bridge sollte nun so aussehen. Ihr seht unter Attributes alle verknüpften Reading/MQTT-Topic Kombinationen. Denkt wieder daran diese Änderung der Konfiguration durch einen Klick auf “Save config” abzuspeichern.

Testing the set MQTT bridge

One way to test the freshly created MQTT bridge is described here.

For this purpose I built a mini MQTT viewer in NodeRed, which shows you the values that are sent to the set topics. “heizung/Arbeitszimmer/temperature” and “heizung/Arbeitszimmer/battery” can be sent. You also have the possibility to send to the topic “heizung/Arbeitszimmer/desiredTemperature” to send the value 25. This has the consequence that - if everything works correctly - the linked radiator thermostat is set to 25°C.

Zuerst prüfen wir nun ob der Empfang und die Übernahme von per MQTT empfangenen Werten funktioniert. Wechselt dazu in den Raum “MAX” und dann in die Detailansicht des jeweiligen Heizungsthermostats.
In the detail view you scroll down until you see the Reading ...

… “desiredTemperature” findet. Dies ist das Reading, dass wir in der Konfiguration der MQTT-Bridge mit dem MQTT-Topic “heizung/Arbeitszimmer/desiredTemperature” have linked. Here you will also see the current value of the reading and the time of the last update.

If you click on the Inject-Node in the self-built MQTT-Viewer you send the value 25 to the Topic “heizung/Arbeitszimmer/desiredTemperature”. So this should now also update the reading of your heating thermostat to the value 25. In addition, the time of the last update is set to the current time.

To test the opposite way - i.e. the publication of a changed reading on an MQTT topic - just scroll to the top of the detailed view of the MAX! heating thermostat. There you change the desired temperature of your heating thermostat as shown.

Dies löst automatisch eine aktualisierung des Readings “battery” aus. Durch die Verknüpfung der MQTT-Bridge mit dem Topic “heizung/Arbeitszimmer/battery” its value is then published via the topic as desired and is then visible via the configured debug node in your NodeRed environment.

Creating an MQTT device using the example of a temperature sensor

Another possibility of the MQTT module is the creation of MQTT devices. This includes all sensors or devices that send their measured values directly via MQTT. In order to collect these values and combine them in a virtual sensor, you must create an MQTT device.

In diesem Beispiel haben wir in unserem Netzwerk einen Temperatursensor, der in regelmäßigen Abständen den gemessenen Temperaturwert per MQTT-Topic “Umgebungsdaten/keller/Temp” versendet. Um diesen nun zu erfassen wird zuerst mit folgendem Befehl ein MQTT-Device angelegt.

define kellerSensor MQTT_DEVICE
Der Befehl setzt sich dabei wieder wie folgt zusammen “define Name-des-Mqtt-Devices MQTT_DEVICE”. Da wir in diesem Beispiel einen Temperatursensor einbinden der sich im Keller befindet nennen wir das MQTT_DEVICE “kellerSensor. Der komplette Befehl zum erstellen des MQTT_Devices lautet also “Umgebungsdaten/keller/Temp”.
Nach dem Ihr das MQTT_Device erstellt habt findet Ihr diesen im Raum “Unsorted”. Darüber könnt Ihr auch die abgebildete Detailansicht öffnen.

Bevor dieses MQTT_Device nun Werte anzeigen kann muss es natürlich zuerst mit dem gewünschten MQTT-Topic verknüpft werden. In diesem Beispiel wollen wir alle auf dem MQTT-Topic “Umgebungsdaten/keller/Temp” eingehenden Werte im erstellten MQTT-Device anzeigen lassen.

To do this, you need to set the following attribute:

attr kellerSensor subscribeReading_Temp Ambient Data/keller/Temp

Dies bewirkt, dass im erstellten MQTT_Device “kellerSensor” das Reading “Temp” erstellt und mit dem abonierten Topic “Umgebungsdaten/keller/Temp” verknüpft wird.

In der Ansicht der Readings taucht nun also auch das Reading “Temp” mit dem aktuellen bzw. zuletzt empfangenen Wert und dem Datum der letzten Aktualisierung auf.

Um die Ansicht nun noch etwas aufzuhübschen könnt Ihr mit folgendem Attribut angeben, dass dem Wert des Readings Temp ein “°C” angehängt werden soll.

attr kellerSensor stateFormat Temp °C
Gebt dazu den Befehl “attr kellerSensor stateFormat Temp °C” in die Befehlszeile Eurer FHEM-Instanz ein.
Dadurch wird die aktuelle Temperatur des “kellerSensors” nun auch mit einem “°C” versehen und es ist direkt ersichtlich, dass es sich dabei um einen Temperaturwert handelt.

More information

https://wiki.fhem.de/wiki/MQTT_Einf%C3%BChrung


Have fun with the project

I hope everything worked as described for you. If not or you have questions or suggestions please let me know in the comments. I will then add this to the article if necessary.
Ideas for new projects are always welcome. 🙂

PS Many of these projects - especially the hardware projects - cost a lot of time and money. Of course I do this because I enjoy it, but if you think it's cool that I share the information with you, I would be happy about a small donation to the coffee fund. 🙂

Buy Me a Coffee at ko-fi.com       

One comment

  1. Hi Fab
    Thank you so much for all of the information you have made available here. I have spent many years with home assistant, and no time at all with FHEM which I am now using to try to get better control of my FHT heating devices. If I can get FHEM communicating with an existing MQTT server that would be my dream.

    I have FHEM running on Raspian OS within a docker container, the install went as per your advice with no errors – but when I try to enter the commands via FHEM web front end I get Cannot load module MQTT_BRIDGE or Cannot load module MQTT_CLIENT which makes me think either I've messed up not installing the perl/mqtt from within the docker container or I've not done something within FHEM to invoke the new MQTT capability?

    Kind regards

    Nick

Kommentar hinterlassen

Your email address will not be published. Erforderliche Felder sind mit * markiert

This site uses Akismet to reduce spam. Learn how your comment data is processed.