Display Raspberry Pi CPU temperature and display it in Openhab with MQTT

Display Raspberry Pi CPU temperature and display it in Openhab with MQTT

In this post I am going to show you how you get the CPU temperature of your Raspberry Pi and display it in Openhab with MQTT. For me this was necessary initially to see when the temperature was increasing so that I can find out how to optimize the fan usage of the Raspberry Pi.

Setting up the Raspberry Pi to read the temperature

The following script can be used to publish the CPU temperature of the Raspberry Pi to an MQTT topic. You will need to change the broker variable to your correct MQTT broker and the topic to the topic you want it to be published.

import random
import time

from gpiozero import CPUTemperature
from paho.mqtt import client as mqtt_client
from datetime import datetime

broker = '192.168.xxx.xxx'
port = 1883
topic = "your/topic/cpu_temp"
client_id = f'python-mqtt-{random.randint(0, 1000)}'

def connect_mqtt():
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %d\n", rc)
    # Set Connecting Client ID
    client = mqtt_client.Client(client_id)
    #client.username_pw_set(username, password)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client

def publish(client):
     temp=CPUTemperature().temperature
     msg = "{{ temp: {0:.2f}, timestamp: {1} }}".format(temp, time.time())
     result = client.publish(topic, msg)
     # result: [0, 1]
     status = result[0]
     if status == 0:
       print(f"Send `{msg}` to topic `{topic}`")
     else:
       print(f"Failed to send message to topic {topic}")

def run():
    client = connect_mqtt()
    client.loop_start()
    publish(client)


if __name__ == '__main__':
    run()

To execute the script succesfully you will need two python libraries to be installed:

pip3 install gpiozero
pip3 install paho-mqtt

The script defines two methods:

  • connect_mqtt: Establishes the connection to the MQTT server
  • publish: Publishes the message. This can be optimized and the temp could be a parameter.

You can run the script by storing the above source with your favorite text editor in e.g. your home directory: ~/cpu_temp.py

As next step add the execution of the script to your crontab:

Open crontab

crontab -e

Execute script every 5 minutes

*/5 * * * * * python3 /home/pi/cpu_temp.py

Setting up Openhab with MQTT

In order to read the data you will need a MQTT bridge reading the published message. You can read about setting up Openhab and MQTT here.

Now you need to add a channel to your MQTT bridge:

  Thing topic rpi_cpu_temp "RPi " @ "Office" {
    Channels:
      Type number : Temp [stateTopic="rpi/office/cpu_temp", transformationPattern="JSONPATH:$.temp"]
  }

And then add an item to your items file:

Number GF_Office_RPi_Temperature "RPi Temperature [%.1f °C]"   <temperature>  (GF_Office)    ["Measurement", "Temperature"]    {channel="mqtt:topic:MyMQTTBroker:rpi_cpu_temp:Temp"}

Last but not least, add it to your Sitemap:

Frame label="Ground Floor" icon="groundfloor" {
    Text label="Office" icon="office" {
        Frame label="Temperature & Humidity" icon="temperatur" {
			Default item=GF_Office_RPi_Temperature
		}
	}
}

That's it, now you can see the temperature of the Raspberry Pi in your Openhab.