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

- platform: mjpeg
mjpeg_url: http://localhost:8081
name: Salon

Install motion :

sudo apt-get install motion

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

daemon on
stream_port 8081
stream_quality 80
stream_maxrate 12
stream_localhost on

And then restart motion :

sudo service motion restart

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

mqtt: #I pass the mqtt setup process
port: 1883
client_id: home-assistant
keepalive: 60
protocol: 3.1

- platform: mqtt
state_topic: "living_room/cam1"
name: cam1
sensor_class: motion

Install mosquitto-clients :

sudo apt-get install mosquitto-clients

The commande to start a motion event is :

mosquitto_pub -r -i motion-cam1 -t "living_room/cam1" -m "ON" 

-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:

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"

And restart motion ! And it’s finished !