[SOLVED] Send temperature from RPi to Qnap OpenHAB

Hi,
i have a sensor connected to RPi and would like it to send temperature to openHAB.
Is it possible?
Where would I start?
thanks

So you have code (python?) that reads the temp from the sensor?

So the easiest way is to use Mqtt (Paho mqtt in python) to publish a topic.

Then on your openHAB server you’ll need the mosquito/mqtt binding and with an item to receive a state from mqtt on the topic that your code publishes.

Sorry I can’t paste any code in here as I’m in a phone. But I’ve used all the correct terms for you to make searching easier. I have all the code that you want and if you get stuck I can post it. Basically it’s a timed loop that on each loop will read the temp and post it.

Hello there,

yes i got python script that reads the sensor.


so i guess i need to include the sensor script into a mqtt python script and publish the topic

if you get a chance to share the scripts would be great but thanks for the terms as i didnt know what to search

cheers

Hi

So I use the AdaFruit library as a basis, but here’s my MQTT script

https://github.com/psyciknz/OpenHAB-Scripts/blob/master/mqtt.channel.py

It has a default update period of 300 seconds, and is currently set to a DHT22 sensor. If you have a difference sensor you may need to update that.

Here is the item in the openhab config that reads the mqtt topic mentioned in the script:
Number gf_cupboard1_temperature_sensor {mqtt="<[mosquitto:cupboard/temperature1:state:default]"}

And the MQTT transport in the openhab.cfg file:
################################# MQTT Transport ######################################
#
# Define your MQTT broker connections here for use in the MQTT Binding or MQTT
# Persistence bundles. Replace with a id you choose.
#

# URL to the MQTT broker, e.g. tcp://localhost:1883 or ssl://localhost:8883
mqtt:mosquitto.url=tcp://localhost:1883

# Optional. Client id (max 23 chars) to use when connecting to the broker.
# If not provided a default one is generated.
#mqtt:<broker>.clientId=<clientId>

# Optional. User id to authenticate with the broker.
# mqtt:<broker>.user=<user>

# Optional. Password to authenticate with the broker.
#mqtt:<broker>.pwd=<password>

# Optional. Set the quality of service level for sending messages to this broker.
# Possible values are 0 (Deliver at most once),1 (Deliver at least once) or 2
# (Deliver exactly once). Defaults to 0.
mqtt:mosquitto.qos=1

# Optional. True or false. Defines if the broker should retain the messages sent to
# it. Defaults to false.
#mqtt:<broker>.retain=<retain>

# Optional. True or false. Defines if messages are published asynchronously or
# synchronously. Defaults to true.
#mqtt:<broker>.async=<async>

# Optional. Defines the last will and testament that is sent when this client goes offline
# Format: topic:message:qos:retained <br/>
#mqtt:<broker>.lwt=<last will definition>

Hi I keep getting invalid syntax warnings on your python code around the usage part.

any help would be appreciated

thanks

In this file? mqtt.dhtsensor.py

What line?

#==================================================================================================================================================
#Usage
#python mqtt.channel.py <temp topic> <humidity topic> <gpio pin> <optional update frequency>
# eg python mqtt.channel.py 'cupboard/temperature1' 'cupboard/humidity1' 4
# will start an instance using 'cupboard/temperature1' as the temperature topic, and using gpio port 4 to talk to a DHT22 sensor
# it will use the default update time of 300 secons.
#==================================================================================================================================================

when i remove # and eg i get a syntax error

Hang on, i think ive totally got the wrong end of the stick here

Sorry mate, ive been at this code for days and have tried so many different ways.

Now im getting a ‘broken pipe’ error after running the python code,

Date Time:   2018-06-26 19:42:13
Temperature: 25.10 C
Humidity:    44.00 %
Updating cupboard/temperature1
Updating cupboard/humidity1
[Errno 104] Connection reset by peer
MQTT Updated result 0 and 1
Append error, logging in again: Result for one message was not 0

Full code here

#!/usr/bin/python
# DHT Sensor Data-logging to MQTT Temperature channel

# Requies a Mosquitto Server Install On the destination.

# Copyright (c) 2014 Adafruit Industries
# Author: Tony DiCola
# MQTT Encahncements: David Cole (2016)

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import json
import requests
import sys
import time
import datetime
import paho.mqtt.client as mqtt
import Adafruit_DHT


#==================================================================================================================================================
#Usage
#python mqtt.channel.py <temp topic> <humidity topic> <gpio pin> <optional update frequency>
# eg python mqtt.channel.py 'cupboard/temperature1' 'cupboard/humidity1' 4
# will start an instance using 'cupboard/temperature1' as the temperature topic, and using gpio port 4 to talk to a DHT22 sensor
# it will use the default update time of 300 secons.
#==================================================================================================================================================

# Type of sensor, can be Adafruit_DHT.DHT11, Adafruit_DHT.DHT22, or Adafruit_DHT.AM2302.
DHT_TYPE = Adafruit_DHT.DHT22

# Example of sensor connected to Raspberry Pi pin 23
DHT_PIN  = sys.argv[3]
# Example of sensor connected to Beaglebone Black pin P8_11
#DHT_PIN  = 'P8_11'

if (len(sys.argv) < 2):
   raise  ValueError('Input arguments of mqtt channel temperature humidity not passed')

MOSQUITTO_HOST = 'localhost'
MOSQUITTO_PORT = 1883
MOSQUITTO_TEMP_MSG = str(sys.argv[1]) # Old channel name in here
MOSQUITTO_HUMI_MSG = str(sys.argv[2]) # Old channel name now passed by argument
print('Mosquitto Temp MSG {0}'.format(MOSQUITTO_TEMP_MSG))
print('Mosquitto Humidity MSG {0}'.format(MOSQUITTO_HUMI_MSG))

# How long to wait (in seconds) between measurements.
print "Args length: " + str(len(sys.argv))
FREQUENCY_SECONDS      = 30000

if (len(sys.argv) > 4):
	FREQUENCY_SECONDS = float(sys.argv[4])


print('Logging sensor measurements to {0} every {1} seconds.'.format('MQTT', FREQUENCY_SECONDS))
print('Press Ctrl-C to quit.')
print('Connecting to MQTT on {0}'.format(MOSQUITTO_HOST))
mqttc = mqtt.Client("mosquitto")
try:

    while True:
        # Attempt to get sensor reading.
        humidity, temp = Adafruit_DHT.read(DHT_TYPE, DHT_PIN)

        # Skip to the next reading if a valid measurement couldn't be taken.
        # This might happen if the CPU is under a lot of load and the sensor
        # can't be reliably read (timing is critical to read the sensor).
        if humidity is None or temp is None:
           time.sleep(2)
           continue

        currentdate = time.strftime('%Y-%m-%d %H:%M:%S')
        print('Date Time:   {0}'.format(currentdate))
        print('Temperature: {0:0.2f} C'.format(temp))
        print('Humidity:    {0:0.2f} %'.format(humidity))

        # Publish to the MQTT channel
        try:
     	    mqttc.connect(MOSQUITTO_HOST,MOSQUITTO_PORT);
            print 'Updating {0}'.format(MOSQUITTO_TEMP_MSG)
            (result1,mid) = mqttc.publish(MOSQUITTO_TEMP_MSG,temp)
            print 'Updating {0}'.format(MOSQUITTO_HUMI_MSG)
	    time.sleep(1)
            (result2,mid) = mqttc.publish(MOSQUITTO_HUMI_MSG,humidity)
            print 'MQTT Updated result {0} and {1}'.format(result1,result2)
            if result1 == 1 or result2 == 1:
                raise ValueError('Result for one message was not 0')
	    mqttc.disconnect()

        except Exception,e:
            # Error appending data, most likely because credentials are stale.
            # Null out the worksheet so a login is performed at the top of the loop.
	    mqttc.disconnect()
            print('Append error, logging in again: ' + str(e))
            continue

        # Wait 30 seconds before continuing
        print('Wrote a message tp MQQTT')
        time.sleep(FREQUENCY_SECONDS)

except Exception as e:
    print('Error connecting to the moqtt server: {0}'.format(e))


have you tried dropping the 2nd publish and seeing if it continues properly?

Hmm another thing I’ve seen this before, I’d moved between systems and used the same script…and what was happening was it was running of both systems with the same client id…and mosquitto was kicking them off. Maybe look at the debug logs for mosquitto.

Are you running in background or foreground, and are you sure there’s only one running.

1 Like

Ok we’re getting close, i did mosquitto -v and it said its had a second broker open or something so i did sudo kill 2345 and have fixed to broken pipe error, did a fresh install of mosquitto on openhabian and BINGO it works!!!

Thanks for your help

Mosquitto Temp MSG cupboard/temperature1
Mosquitto Humidity MSG cupboard/humidity1
Args length: 4
Logging sensor measurements to MQTT every 30000 seconds.
Press Ctrl-C to quit.
Connecting to MQTT on 192.168.0.136
Date Time:   2018-06-26 22:00:13
Temperature: 25.70 C
Humidity:    44.60 %
Updating cupboard/temperature1
Updating cupboard/humidity1
MQTT Updated result 0 and 0
Wrote a message tp MQQTT


Sorry to be a pain but I’m now struggling to start the python code with Cron or rclocal etc.

Any help will appreciated

scrap that comment…its working :slight_smile: