RPi sensor + MQTT

Hello,

So I have my RPi sensor HC-SR501 connected on the RPi which I’ve managed to get some readings (motion detected), using a python script I’ve found on several tutorials online, but I cannot warp my head around on how to connect it with MQTT which is running on my RPi, so I can do some automation, like turning the light on let’s say.

Can any one please help me out :slight_smile:

Thank you !

please no one ?

You should try to be a bit more descriptive of your setup. Is your HASS running on the same RPi? If so, why are you trying to send an MQTT message from a node to itself? HASS running on an auxiliary RPi? Maybe add an excerpt of your python script?

Hi thanx for replying !

HA running on the same RPi as the HC-SR501 motion sensor is connected to.

Maybe i just have it wrong in my head on what i’m trying to achieve :confused:

All i want to do is pick up if there is any motion from the sensor and do some automation with it.

Is the MQTT approach wrong ?

Could please guide me to the right direction if possible ?

Thank you so much :smiley:!

It’s not ‘wrong’ but it sounds overly complicated given that the motion sensor and home-assistant are on the same device. Without knowing much about your python script, I would remit providing more support, but I believe that this component https://home-assistant.io/components/binary_sensor.rpi_gpio/ was devised for the exact purpose that you are trying to tackle. Personally I’ve never used this component, but it’s a step in the right direction.

Hi,
Here is what I have tried to use with a cheap chinese motion sensor.
I have to say that I not using this now, but it is not because this script is not working but it is because I could not get the correct sensitivity set on the damn thing :frowning:

#!/usr/bin/python
import sys
import mosquitto, os, urlparse
from time import sleep
import RPi.GPIO as GPIO


pin = 21
GPIO.setmode(GPIO.BCM)

GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

# Define event callbacks
def on_connect(mosq, obj, rc):
    print("rc: " + str(rc))

def on_message(mosq, obj, msg):
    print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload))

def on_publish(mosq, obj, mid):
    print("mid: " + str(mid))

def on_subscribe(mosq, obj, mid, granted_qos):
    print("Subscribed: " + str(mid) + " " + str(granted_qos))

def on_log(mosq, obj, level, string):
    print(string)

def motionSensor(channel):
    if GPIO.input(pin):
        global counter
        counter += 1
        print "Movement " + str(counter)
        # Connect
        mqttc.username_pw_set(url.username, url.password)
        mqttc.connect(url.hostname, url.port)

        # Start subscribe, with QoS level 0
        mqttc.subscribe("movement", 0)

        # Publish a message
        mqttc.publish("movement/kitchen", str(counter)) 

GPIO.add_event_detect(pin, GPIO.BOTH, callback=motionSensor, bouncetime=150)
counter=0


mqttc = mosquitto.Mosquitto()
# Assign event callbacks
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_publish = on_publish
mqttc.on_subscribe = on_subscribe 

url_str = os.environ.get('CLOUDMQTT_URL', 'mqtt://192.168.112.254:1883')
url = urlparse.urlparse(url_str)



try:
   while True:
       sleep(1)

finally:
    GPIO.cleanup()
    print "All cleaned up" 

This is using mosquitto as mqtt server and the script is python.
Hope you have better luck…

cheers
tom

Just checked you’re motion sensor on google and it looks the same as mine. So please post if you have an luck with it. :slight_smile:
I forgot to mention that you have to set up an mqtt sensor in HA where the value of the counter variable appears. And you can do automations based on that.

Ooops, I really need to be more accurate in reading. I hava HA running on a differnet machine then my rpi. So maybe this is an overkill for the subject. Sorry…

I have 4 of these sensors controlled by arduinos and esp8266s, and they do seem sensitive to electrical noise, which may be why you were having difficulty with the sensitivity, as the Pi will be generating more noise. You may need to have some longer wire to move the sensor physically away from the Pi.

The advantage of using MQTT in this situation is of future flexibility. If you want to move HA to a different machine in the future it will be relatively straightforward if you are using MQTT, but if you are using the GPIO pins directly, you will have to reconfigure the sensor.

Also, if you want to switch away from HA and use a different controller, it would also be fairly easy as they all support MQTT.

So thank you guys for the help, you are awesome :D!

@redwngsrul I will check this approach, thanx !

@towme this is what i had in mind, I’ve change the script according to my needs, it works yey! but i use paho.mqtt.client instead to connect.

The last thing I’m stuck is to trigger the automation:

- alias: Turn on the lights
    trigger:
      platform: mqtt
      topic: movement/bedroom/lights
      payload: 'on'
    action:
      service: homeassistant.turn_on
      entity_id: light.my_bedroom  

but i get confused with payload (i think that is the issue) and how to actually trigger the event :confused:

@gpbenton yes this what I’m thinking to do at some point, but i have to learn how this all works with HA.

edit:

also the sensor part:

- platform: mqtt
  name: "Motion lights"
  state_topic: "movement/bedroom/lights"
  qos: 0
  payload_on: "on"
  payload_off: "off"
  sensor_class: motion

They were in a different room (so at least 3 m away), but the pir sensor was getting the 5 volts from the pi gpio. I have just learned that you can power these with anything from 5 - 20 volts, so I can connect the power and ground to a separate power supply. I will give them another try this weekend.
tom

The script I pasted sends numbers to the mqtt server. Each time the sensor is tripped the counter variable increases. Then at some point it is restored to zero.
With mosquitto you have a command mosquitto_sub, with which you can read the different topics or sub topics your mqtt server has. (eg.: mosquitto_sub -h localhost -t movement/kitchen/#)
So I have created a sensor which showed the ‘counter’ variable as a value in HA, and the automation checked if the sensor value was 0 or not.

Maybe this is not sophisticated enough, but for a start I as trying to achieve to turn on the kitchen lights, when my wife cooks and the sun in under a certain level.

But the problem was that it either did not turn on when I was dancing in the kitchen, or it turned on when nobody was there in the middle of the night. :frowning:

cheers
tom

update:

I went with @redwngsrul suggestion, since mqtt was too big of a fuss to work and it doesn’t make sense if it’s locally on the RPi itself.

component https://home-assistant.io/components/binary_sensor.rpi_gpio/ just works :slight_smile:

Thank you again guys for the help !

ps: I will come back to this at some point when I get my hands on some ESP8266 .

Hi @towme, how did your setup go ? Are you still improving your setup or have your way by any other means?Your code looks interesting, however didn’t get it what are you doing with subscription here. I tested this motion sensor with Arduino and tuning the resistor value, I was able to test it reliably. Though, haven’t got a chance to see how it’s performing in real life scenario.

I am interested to know how others are doing this kind of things… I am planning to make some kind of super sensor node ( either on a pi zero W or Arduino with esp8266 most likely pi). At this moment I have the pir sensor, dht sensor and lux sensor. I am trying to combine the information of lux and temp/humidity together, motion should be separate information as it needs quick triggering and fast sending. Frequency of 120s for temperature​ won’t harm but for pir sensor, 1s might be the way to go. However, long story short, I am planning to use paho-mqtt rather mosquito client. Anyone any thoughts?

The miFlora sensor is very cheap and has many of the sensors you are describing.
For sensor nodes a platform I am experimenting with is https://www.zerynth.com/ which has libraries for MQTT etc. Also read https://home-assistant.io/blog/2016/08/31/esp8266-and-micropython-part2/

Right now I do not have any motion sensor working.
I have an arduino lying around, so I thought that the same as you, that it would make a fantastic sensor host.
So this led me to mysensors.org, but I found that a bit overkill.
then I still had to find a way to get the arduino talk to the mqtt, which I could not solve.
Then I thought about find as in (www.internalpositioning.com) but that requires you to carry a wifi capable device with you

HA 0.40 introduces android IP cam sensor, so mybe those can be used for motion sensing, but this means you need to put an adroid device everywhere where you wish to detect motion…

cheers
tom

Thanks to both of you for your kind and thoughtful reply.

@robmarkcole I checked the miflora sensor, looks interesting but as its missing the motion sensor component which is kind of my primary requirement so it wont be in any use. I didn’t heard of Zenryth before, it looks promising, I might have a closer look. Regarding the micro python, I read that blog before and bought few ESP8266 modules that time but I never got the courage to test it out thoroughly on the other hand, pi zero looks easier with paho-mqtt library. May be I will go to other route before pi zero with paho-mqtt fails.

@towme, I tested the HC-SR501 sensor with my Arduino, in my testing it worked reliably after tuning the sensitivity and the sleep interval inside Arduino code. However, out of the box, it was too sensitive and even triggered motion if there was a shadow or change in light. May be it wont behave the same if I use it out of the testing environment. I will update after completing my current project with pi zero.

1 Like

Just an update on my sensor project. Actually while I was trying to tinker with my multiple sensors with pi zero, at the same time I learnt about the ESPEasy firmware. So, paused for a moment and went for a quick testing with my ESP12E board lying idle in my electronics repo. And to my wonder, it was decently easy with this firmware to setup multiple sensors within no time.

Though initially there was few hiccups related to MQTT but later I figured out it was simply a case of the firmware version. After I choose the right one, it was damn easy. Now, as expected my little made custom box is reporting Temp/Humidity, Lux in 10mins interval and sending alert as soon as motion is detected. Happy me :slight_smile: I do have plan for enhance the efficiency of this thing by adding some more sensors; probably Smoke and Gas detection would be the next line of fire.

If anyone is interested on the ESPEasy with ESP nodes, here is an interesting thread.

Thanks & Regards
Tarikul