Connecting the motion sensor, alarm and video recording in Home Assistant on Raspberry pi

I’d like to tell you about my little experience of working with Home Assistant (hereinafter – HA) on Raspberry pi. Further I’ll speak about connecting the video registration functionality, the motion sensor and, accordingly, the home security function with receiving photos by e-mail  in case of triggering “security”.

Of course, one of the reasons is the desire to understand from your reviews what I “did wrong” when implementing this scenario.

There are three ways to configure the above functionality: “with no problem”,” short” and “independent”. In the first case, you can download the developed image from the site https://ViaMyBox.com/downloadpage 

for your Raspberry pi, and you can see how everything looks in the already configured form. In the second case, you can download the zip from the site or from the github project, install it and then install the HA docker image through the utility (sudo via-setup.sh) to see how everything is set up.  And finally, the third way is to set up “everything in your own way”: take something useful from the site or githab project, or from this tutorial. Links to all this you will find at the end of the article.

Assume that you already have a running Home Assistant (HA). In this article, we will only consider the aspects of creating yaml configurations and describing the sequence of rules and conditions that lead to a specific action. In our case, the action is the connection of the “security” mode and the triggering of the script, which starts taking photos within 5 seconds after the motion sensor is activated. And as a result, Home Assistant sends the captured photos by mail. I’m not an expert on yaml or creating configurations for Home Assistant, but following the working examples, I got a working configuration that I want to share.

All the files that we will contact, I will lay out at the end of the article for more convenient consideration. I’m not going to touch on how video recording scripts work in bash or python in this example. We will speak about Home Assistant only. But if you have any questions – you are Welcome!

In the end, I have everything looks like this (red highlighted what we will consider in the article):

Naturally, I use Raspberry pi as a platform. And my path to the configuration files is /usr/share/hassio/homeassistant/ . The path to your configuration files may differ from my path. At that time, I had Home Assistant 0.101.3. We will be interested in the configuration files in this directory: configuration.yaml and automation.yaml.

After each change to these files, it is important to remember that you will need to check the configuration after our changes for possible errors made in it. This is done in the Home Assistant dashboard -> Configuration -> Server Controls -> Check Config. And then, in the same place, we do Reload Automations, and Reload Scripts, if the check was successful. And, if in doubt, Server  Management restart the configuration updates exactly in the same tab.

The HC-SR501 motion sensor is connected to the Raspberry pi GPIO bus. It is necessary to connect the three contact wires to the GPIO correctly, and we will be able to use our sensor in action. The sensor has three contacts: power gcc (+), zero gnd ( -), control contact (data). After reading the description of GPIO, I connected them to my raspberry as follows. I connected the HC-SR501 to the GPIO connector: pir#2 – 5.5 vvcc; pin#26 (13 row) – data contact and pin#6-GND ( – ) of the sensor.

As a photo source, I use either a usb camera or a csi camera in conjunction with mjpg-streamer. We will not describe how to install and configure mjpg-streamer on Raspberry pi in this post. There are many examples of quick installation in the Internet. However, I want to say that I use data from this project https://github.com/cncjs/cncjs/wiki/Setup-Guide:-Raspberry-Pi-%7C-MJPEG-Streamer-Install-&-Setup-&-FFMpeg-Recording  The installation of this module is also described in details there. Or use any method that is convenient for you to get photos and videos. After all, it’s up to you to decide which bash script to attach to HA.

Let’s describe our sensor now in configuration.yml, let’s say, via the command line:

sudo nano /usr/share/hassio/homeassistant/configuration.yaml

although using notepad++ with winscp can be more convenient..

Let’s describe the sequence of settings for HC-SR501 as follows:

binary_sensor:
  - platform: rpi_gpio
    #name: HC-SR501
    ports:
      7: Sensor HC-SR501
    invert_logic: false

It should be noted that here an important point is played by the settings in the lines that describe the connection to the control (data) contacts of the sensors:      pin#7

ports:

      7: Sensor HC-SR501

Home Assistant has a built-in tool for enabling the home security feature. Let’s describe it in our configuration.yaml, using the description: https://www.home-assistant.io/integrations/manual/

  
alarm_control_panel:
  - platform: manual
    name: Home Alarm
    pending_time: 60
     delay time 40
     triggered:
    pending_time: 0
    code: 1234

This setting means that we have 60 seconds to leave the house (after this time, the alarm will turn on), and 40 seconds to turn it off (with the password 1234) when we return home. For some reason, you always leave longer than you come.)

We will now describe the mechanism for enabling and disabling photography when the motion sensor is triggered in our configuration.yaml (more information about the switch – command_line platform can be found here https://www.home-assistant.io/integrations/switch.command_line/):

 - platform: command_line
   switches:
      start_stop_motion_rec_timelapse:
        friendly_name: 'Record motion timelapse video'
        command_on: 'curl http://localhost/start_mjpgstrm.php  && curl http://localhost//rec-motion-mjpg.php'
        command_off: 'curl http://localhost/stop_mjpgstrm.php && curl http://localhost/rec-motion-mjpg-stop.php'

Here we have linked the command_on enable and command_off disable commands to our scripts that control camera recording. In this case, when you enable command_on, 2 scripts are executed sequentially. This starts mjpg-streamer and starts recording on the motion sensor. Access to bash scripts goes through the php file of the working site on the Raspberry pi. To do this, I set up nginx and web access, and when accessing through the browser as http://<ip address of your Raspberry pi>/start_mjpgstrm.php  should execute our php script.

We do not consider setting up web access in this article. Clearly, this is not secure, but due to the fact that I have HA on docker, I am faced with the fact that I have an isolated docker environment. And the “external world” of the OS I can see by accessing my site via php. There are probably a bunch of right solutions from docker or HA guru. Please, write, it would be interesting to know! 

I will leave the listing of these scripts under the article, and we will not dwell on them. In this article, I want to follow only the formation of a sequence of actions in Home Assistant.

All this is placed in the start_stop_motion_rec_timelapse object, which will be our visual switch, with which we will manage the recording of photos when the motion sensor is triggered.

We will be able to visualize these objects created by us in the Home Assistant- > Overview tab by switching the activation of Configure UI configuration mode in the upper right corner

confugure ui

Pre-reboot the HA in the browser in the “Configuration -> Server Control” tab to pick up our configuration.yaml.

Next, select the yellow plus at the bottom of the browser window, click the Entities card and link our created objects to the maps.

For our sensor, select the sensor card. It will look like this:

As you can see in the picture, the second entity field contains the above-described switch: switch.start_stop_motion_rec_timelapse.

It allows us to turn our motion sensor recording on and off, regardless of whether the “home security” function is enabled. And, in general, it should already work after all the above described actions.

 And, accordingly, we add the alarm panel map:

There is another interesting point here. I use Home Assistant as a docker container. In this regard, the path to our script will differ from the actual path to the script file. After all, the file structure inside the container is virtualized and linked to the actual file structure via docker mounted volumes. This looks, for example, like this: Path inside the container: /config/scripts/ Path inside the OS: /usr/share/hassio/homeassiatnt/scripts. So look at the settings of your container, how these volumes are configured in the Binds field. If you have HA there.

sudo docker inspect homeassistant|less

When the motion sensor is triggered, at the moment when the alarm is activated: I want that in addition to the fact that we start taking quick photos (timelapsesnapshots), I would receive a warning in the mail and a picture. I parallelized the processes. In the first case, photo – logging (timelapsesnapshots) occurs within a few seconds after the sensor is triggered. To do this, I run mjpg-streamer curl http://localhost/start_mjpgstrm.php , start php: сurl http://localhost/rec-motion-mjpg.php . It, in turn, runs python script mov.py. All described files and bundles are available at the end of the article by the link.  And another script takeSnapshotWebcam.sh takes a picture that I send in an email. I describe these scripts in our configuration.yml this way:

shell_command:
#start the script that generates a snapshot for the mailing list
  take_snapshot_webcam: '/config/scripts/takeSnapshotWebcam.sh'
#starting our mjpg-streamer 
  start_mgpg_streamer: 'curl http://localhost/start_mjpgstrm.php'
#stopping mjpg-streamer
  stop_mgpg_streamer: 'curl http://localhost/stop_mjpgstrm.php'
#start the script that generates snapshots for 5 seconds
  start_motion_rec: 'curl http://localhost/rec-motion-mjpg.php'
#stop it
  stop_motion_rec: 'curl http://localhost/rec-motion-mjpg-stop.php'

In the same configuration.yml describing our object for mailing:

notify:
  - name: ha_sendmail
    platform: smtp
#if mail is on gmail
    server: smtp.gmail.com
    port: 587
    timeout: 15
#from whom we send
    sender: user@gmail.com
    encryption: starttls
    username: user@gmail.com
    password: passwd
#to whom we send (you can use one box and send it to yourself, why not)
    recipient:
      - user@gmail.com
    sender_name: My Home Assistant

Important point! In order for our HA to be able to connect and send emails (the sender field), we must allow our HA service to use this mailbox on gmail. How to do this-link here: https://myaccount.google.com/lesssecureapps

And further, we describe the automation mechanism itself when enabling the home_alarm alarm in automation.yaml:

#first action bundle (alias “triggered by sensor if security is enabled”
- alias: 'Trigger alarm while armed away'
#alias is triggered when the sensor is in the “on” position
  trigger: 
    - platform: state
      entity_id: binary_sensor.sensor_hc_sr501
      to: 'on'
#provided that the security mode is enabled in the absence of people at home “armed away”
  condition:
    - condition: state
      entity_id: alarm_control_panel.home_alarm
      state: armed_away
#and then performs the action 
  action:
#Running mjpg-streamer (if disabled)
    - service: shell_command.start_mgpg_streamer
#Running a script that records from the camera
    - service: shell_command.start_motion_rec
#Change the visualization of our "Home security" card on the HA panel to the “alarm triggered” position
    - service: alarm_control_panel.alarm_trigger
      entity_id: alarm_control_panel.home_alarm

The next set of conditions and actions is to send a console message when “security” is turned off and turn off our motion recording scripts.

- alias: 'Send notification when alarm is Disarmed'
  trigger:
    - platform: state
      entity_id: alarm_control_panel.home_alarm
      to: 'disarmed'
  action:
    - service: shell_command.stop_mgpg_streamer
    - service: shell_command.stop_motion_rec
    - service: persistent_notification.create
      data:
       message: The alarm is Disarmed at {{ states('sensor.date_time') }}"

And finally, the third link-send an email with a photo:

- alias: 'Send notification when alarm triggered'
  trigger: 
   - platform: state
     entity_id: alarm_control_panel.home_alarm
     to: 'triggered'
  action:
    - service: persistent_notification.create
      data:
       message: Notification when alarm triggered. Motion sensor HC-SR501 detected.
    - delay:
       seconds: 4
#run our script for creating a single script
    - service: script.webcam_snapshot
#and refer to the described object in configuration.yaml: notify.ha_sendmail
    - service: notify.ha_sendmail
      data:
        title: 'Intruder alert'
        message: '{{now().strftime("%H:%M %Y-%m-%d")}}:Notification when alarm triggered. Motion sensor HC-SR501 detected.'
        data:
           images:
#link to the script already made by the script.webcam_snapshot
              - /config/camera/snapshot.jpg

Remember that in yaml files, line markup is important, and space characters before commands play an important role in forming code blocks and its structure. Check all changes to your yaml via Home Assistant (hereinafter HA) Configuration -> Server Controls -> Check Config

It seems to be all. And your Raspberry pi turns into something elegant!..)

Here it is working HA automation, configured with your own hands! Be sure to write me everything you think about it!

And, if after all you read to the end, here are the promised links:

Image and zip: https://viamybox.com/downloadpage

Github project: https://github.com/viatc/viamybox

 

Configuration files are described here: configuration.yaml, automation.yaml, takeSnapshotWebcam.sh, rec-motion-mjpg.php, mov.py