In an earlier tutorial I showed how to read the popular DHTxx sensor on a Raspberry Pi and then to MQTT that into Openhab.
However, there are more ways to skin a cat, so what I like to do this time is:
1) Read the sensor with a device tree overlay on a Raspi and then
2) Send the data to OpenHab with the REST-API
I am not saying one method is better than the other, but suppose you dont want to install an MQTT server because all your other channels don’t need MQTT, then the REST API comes in handy.
1) Reading the DHT sensor
First we need to load the dht11 overlay at boot-up
sudo nano /boot/config.txt
obviously one can pick another pin here, or declare a different sensor such as the DHT22 or DHT21 (AM2301)
then all you have to do is to read the following 2 files:
Once you have loaded the overlay and connected your sensor, a simple:
would show you the temperature.
cat /sys/devices/platform/dht11@0/iio:device0/in_humidityrelative_input, would show you the humidity
Upon doing that in a python program, I noticed there can be quite a number of I/O errors. This seems to be a frequent problem with this overlay, so in order not to interrupt the program, I had to do a bit of Error catching.
2) Sending values to OpenHab
The REST API is fairly simple to use. We only need 1 line for every Item we want to update. Such a line looks like this:
The ‘value’-variable needs to be a string.
3) Wrapping it up
A simple Python program would look like so:
import time import requests tfile='/sys/devices/platform/dht11@0/iio:device0/in_temp_input' hfile='/sys/devices/platform/dht11@0/iio:device0/in_humidityrelative_input' def read_temp_raw(): f=open(tfile,'r') lines=float(f.read())/1000.0 f.close() return lines def read_humidity_raw(): b=open(hfile,'r') hlines=float(b.read())/1000 b.close() return hlines while True: try: T=str(read_temp_raw()) print(T) H=str(read_humidity_raw()) print(H) time.sleep(2) #Put your own IP and Itemnames here, requests.put('http://192.168.1.103:8080/rest/items/<ITEMNAME>/state',T) requests.put('http://192.168.1.103:8080/rest/items/<ITEMNAME>/state',H) except IOError: print("I/O error")
Beware that Python programs rely on proper indenting. As this sometimes can be corrupted by publication on a website, I will leave an image of the properly indented program below:
As I am not the world’ s best python coder, I am sure improvements can be made, but at least this code will get you up and running fast.
Since the items are updated through the REST API, they do not need a channel and could look as simple as this:
Number HH "REST Humidity [%.0f %%]" <humidity> (Weather) Number HT "REST temperature [%.1f °C]" <temperature> (Weather)