Home-Assistant : live camera feed and motion detection with a USB camera using motion

I want to display my webcam feed on home assistant. That’s easy and well explained on home assistant’s website. However they do not tell how to implement a motion detection system at the same time.

First step : set up the camera live feed as explained in the docs

In your configuration.yaml

[code]camera:
– platform: mjpeg
mjpeg_url: http://localhost:8081
name: Salon[/code]

Install motion :

[code]sudo apt-get install motion[/code]

Configure /etc/motion/motion.conf (change these values 🙂

[code]daemon on
stream_port 8081
stream_quality 80
stream_maxrate 12
stream_localhost on[/code]

And then restart motion :

[code]sudo service motion restart[/code]

And home assistant, then the webcam should appear ! Yeah !

Now the motion detection. The method I took is to use the mqtt protocol. A binary sensor will be the state of motion detection, motion will publish updates to the given topic to say if motion is on or off, and home assistant will subscribe to it.

Add this in your HA configuration.yaml

[code]mqtt: #I pass the mqtt setup process
broker: 127.0.0.1
port: 1883
client_id: home-assistant
keepalive: 60
protocol: 3.1

binary_sensor:
– platform: mqtt
state_topic: “living_room/cam1”
name: cam1
sensor_class: motion[/code]

Install mosquitto-clients :

[code]sudo apt-get install mosquitto-clients[/code]

The commande to start a motion event is :

[code]mosquitto_pub -r -i motion-cam1 -t “living_room/cam1” -m “ON” [/code]

-r sets the retain flag
-i is just a client id
-t is the topic, which should match the configuration in mqtt
-m Sets the message content, ON for motion being detected, OFF for a still image.

Then we have to update motion.conf accordingly:

[code]on_event_start mosquitto_pub -r -i motion-cam1 -t “living_room/cam1” -m “ON”
on_event_end mosquitto_pub -r -i motion-cam1 -t “living_room/cam1” -m “OFF”[/code]

And restart motion ! And it’s finished !