{"id":1079,"date":"2016-11-14T21:56:30","date_gmt":"2016-11-15T05:56:30","guid":{"rendered":"https:\/\/partofthething.com\/thoughts\/?p=1079"},"modified":"2017-01-02T09:42:16","modified_gmt":"2017-01-02T17:42:16","slug":"getting-ip-camera-motion-events-into-a-home-assistant-to-trigger-things","status":"publish","type":"post","link":"https:\/\/partofthething.com\/thoughts\/getting-ip-camera-motion-events-into-a-home-assistant-to-trigger-things\/","title":{"rendered":"Getting IP camera motion events into Home Assistant to trigger things"},"content":{"rendered":"<p>Oh this is exciting! I&#8217;ve been trying to figure out how to get motion events from my IP camera into my <a href=\"https:\/\/home-assistant.io\">home-assistant <\/a>instance <a href=\"https:\/\/partofthething.com\/thoughts\/?p=937\">running on my Raspberry Pi<\/a>, and I just did a successful test! It works! Hooray. Briefly, I set up an email server on the Pi, have the camera email the Pi, have the email server trigger a script which parses the email for key words and sends MQTT signals as appropriate, at which point the home-assistant MQTT client sees them and triggers automations (like blinking a light to scare people off). Here&#8217;s how I did it.<\/p>\n<figure id=\"attachment_1090\" aria-describedby=\"caption-attachment-1090\" style=\"width: 484px\" class=\"wp-caption aligncenter\"><a href=\"https:\/\/partofthething.com\/thoughts\/wp-content\/uploads\/2016\/11\/Screenshot-from-2017-01-02-05-57-03.png\"><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-1090 size-full\" src=\"https:\/\/partofthething.com\/thoughts\/wp-content\/uploads\/2016\/11\/Screenshot-from-2017-01-02-05-57-03.png\" width=\"484\" height=\"224\" srcset=\"https:\/\/partofthething.com\/thoughts\/wp-content\/uploads\/2016\/11\/Screenshot-from-2017-01-02-05-57-03.png 484w, https:\/\/partofthething.com\/thoughts\/wp-content\/uploads\/2016\/11\/Screenshot-from-2017-01-02-05-57-03-300x139.png 300w\" sizes=\"auto, (max-width: 484px) 100vw, 484px\" \/><\/a><figcaption id=\"caption-attachment-1090\" class=\"wp-caption-text\">Camera-based motion sensors in home-assistant<\/figcaption><\/figure>\n<p><!--more--><\/p>\n<h3>Set up an email server on the Raspberry Pi<\/h3>\n<p>I set up a LAN-only postfix email server on my Raspberry Pi with<\/p>\n<pre class=\"toolbar:2 nums:false highlight:false\"> sudo apt-get install postfix<\/pre>\n<p>and chose the &#8220;internet&#8221; choice so it wasn&#8217;t just local to the Pi. Since I don&#8217;t forward any ports from the real internet to the Pi, this is OK because it&#8217;s isolated on my LAN behind my router.<\/p>\n<p>After some basic config, I tested the system&#8217;s ability to receive emails by sending them from my laptop using Telnet:<\/p>\n<pre class=\"toolbar:2 nums:false lang:default highlight:0 decode:true\">telnet [rpi ip] 25\r\nHELO localhost\r\nmail to: pi@localhost\r\nrcpt from: me@localhost\r\ndata\r\nTesting Email 123\r\n.\r\n<\/pre>\n<p>Note: You can automate this with autoexpect.<\/p>\n<p><span style=\"color: #ff0000;\">NOTE: Do not do this on a public server! If you have any access to the pi from the internet this can put you at risk of becoming a spam drone or worse. If you want set up a legit public email server, you have to do a lost more work.\u00a0<\/span><\/p>\n<h3>Set up email motion alerts from the camera<\/h3>\n<p>Most cameras (foscam, amcrest, etc.) have email options on motion. Have them send an email to the raspberry pi. Trigger the motion event and look at what the emails look like so you can figure out what to read from them to trigger motion alarms and maybe all clears. I used mutt to read emails on the pi, but you can also just view \/var\/mail\/pi with a text editor if you want. Once you&#8217;ve gotten a few emails and can see key phrases in them, you&#8217;re ready for the next step.<\/p>\n<h3>Set up a MQTT server somewhere and a binary sensor<\/h3>\n<p>Home-assistant has some nice info on setting up a MQTT broker. You can use the built-in one (I couldn&#8217;t get it working) or use one on an ubuntu server (my choice since I have a webserver), or you can install one on the pi itself. <a href=\"https:\/\/home-assistant.io\/components\/mqtt\/\">See here for more info<\/a>. This will be the conduit home-assistant reads the signals in from and triggers automations, etc. Here is my config:<\/p>\n<pre class=\"lang:yaml \" >binary_sensor:\r\n  - platform: mqtt\r\n    state_topic: \"home-assistant\/camera\/motion\"\r\n\r\nmqtt:\r\n  broker: !secret remote_server\r\n  port: !secret mqtt_port\r\n  client_id: home-assistant\r\n  keepalive: 60\r\n  username: !secret user\r\n  password: !secret mqtt_pass\r\n  protocol: 3.1\r\n<\/pre>\n<p>Set up automations with the binary sensor now.<\/p>\n<h3>Make a script to parse the incoming emails and trigger MQTT updates<\/h3>\n<p>Now make a script that can parse an email from the camera, scan it for key phrases, and trigger MQTT publishing as necessary. I installed the mosquitto package on my pi to get access to the publishing command. My script looks like this:<\/p>\n<pre class=\"lang:python\">#!\/usr\/bin\/python3\r\nimport sys\r\nimport re\r\nimport subprocess \r\nfrom email.header import decode_header\r\n\r\nMOSQUITTO_LINE = 'mosquitto_pub -h host.com -p 1111 -t home-assistant\/camera\/motion -m \"{}\" -u user -P password --capath \/etc\/ssl\/certs'\r\n\r\ndef parse():\r\n    message = sys.stdin.read()\r\n    device = None\r\n    for line in message.split('\\n'):\r\n            #if re.search('Alarm event: Motion Detect$',line):\r\n            if re.search('Subject: ', line):\r\n                parsed = decode_header(line)\r\n                if 'motion alarm at' in str(parsed[1][0]):\r\n                    trigger_alarm()            \r\n            elif 'Alarm device name:' in line:\r\n                device = ' '.join(line.split()[3:])\r\n  \r\ndef trigger_alarm():\r\n    # publish notice to MQTT server\r\n    subprocess.call(MOSQUITTO_LINE.format('ON'), shell=True)\r\n\r\ndef clear_alarm():\r\n    subprocess.call(MOSQUITTO_LINE.format('OFF'), shell=True)\r\n\r\nif __name__ == '__main__':\r\n    parse()\r\n<\/pre>\n<p>Your will probably look different. This triggers an alarm on an older Foscam camera. Note that I had to actually decode the subject line which was encoded for MIME. For Amcrest, the whole message is MIME encoded so you&#8217;ll have to figure your camera out. This <a href=\"https:\/\/docs.python.org\/3\/library\/email.header.html\">Python email doc<\/a> page was useful. For Amcrest cameras, my code ended up having lines like these:<\/p>\n<pre class=\"lang:python\" >\r\nmsg = email.message_from_string(message)\r\n\r\nfor part in msg.walk():\r\n    if part.get_content_maintype()=='multipart':\r\n        continue\r\n    else:\r\n        print(part.get_payload(decode=True))\r\n<\/pre>\n<p>Giving an email result somewhat like this:<\/p>\n<pre class=\"toolbar:2 nums:false highlight:0 \" >Alarm Event: Motion Detect\r\nAlarm Input Channel: 1\r\nAlarm Start Time(D\/M\/Y H:M:S): 27\/12\/2016 20:05:02\r\nAlarm Device Name: AMC[REDACTED]\r\nAlarm Name: \r\nIP Address: [redacted]<\/pre>\n<p>Anyway, save that file as \/home\/pi\/camera\/alert.py and chmod 755 it to make it executable. Now you&#8217;re on to the final step.<\/p>\n<h3>Tell your email server to pass incoming emails to the script for potential signaling<\/h3>\n<p>In a nutshell, follow the instructions <a href=\"https:\/\/www.thecodingmachine.com\/triggering-a-php-script-when-your-postfix-server-receives-a-mail\/\">from this page<\/a> to point postfix to your script. This will call your script and dump the incoming email to its stdin (which is why we read stdin in the script).<br \/>\nNote that once you do this, you will not get the emails in the inbox anymore. But you don&#8217;t need them if this is all you&#8217;re using the email server for. If you want to have multiple scripts and still get the email, then you have to work harder and set up multiple smtp daemons on different ports and pass them around.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Oh this is exciting! I&#8217;ve been trying to figure out how to get motion events from my IP camera into my home-assistant instance running on my Raspberry Pi, and I just did a successful test! It works! Hooray. Briefly, I set up an email server on the Pi, have the camera email the Pi, have &hellip; <a href=\"https:\/\/partofthething.com\/thoughts\/getting-ip-camera-motion-events-into-a-home-assistant-to-trigger-things\/\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">Getting IP camera motion events into Home Assistant to trigger things<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"activitypub_content_warning":"","activitypub_content_visibility":"","activitypub_max_image_attachments":4,"activitypub_interaction_policy_quote":"anyone","activitypub_status":"","footnotes":""},"categories":[3,69,75],"tags":[],"class_list":["post-1079","post","type-post","status-publish","format-standard","hentry","category-computers","category-electronics-and-physics","category-home-automation"],"_links":{"self":[{"href":"https:\/\/partofthething.com\/thoughts\/wp-json\/wp\/v2\/posts\/1079","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/partofthething.com\/thoughts\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/partofthething.com\/thoughts\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/partofthething.com\/thoughts\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/partofthething.com\/thoughts\/wp-json\/wp\/v2\/comments?post=1079"}],"version-history":[{"count":10,"href":"https:\/\/partofthething.com\/thoughts\/wp-json\/wp\/v2\/posts\/1079\/revisions"}],"predecessor-version":[{"id":1114,"href":"https:\/\/partofthething.com\/thoughts\/wp-json\/wp\/v2\/posts\/1079\/revisions\/1114"}],"wp:attachment":[{"href":"https:\/\/partofthething.com\/thoughts\/wp-json\/wp\/v2\/media?parent=1079"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/partofthething.com\/thoughts\/wp-json\/wp\/v2\/categories?post=1079"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/partofthething.com\/thoughts\/wp-json\/wp\/v2\/tags?post=1079"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}