Email controlled gate opener in 20 lines of shell

Background

Recently while writing and testing some email related code I got annoyed and decided to make an easier way to automate listening for emails and performing actions when they arrive. The result is websocket.email and to demonstrate how easy it is to use, let's make an email controlled gate opener using a raspberry pi and a tiny shell script.

The hardware

The abridged theory

In my gate opener the circuit looks something like this (or can be approximated to it):

When the button is pressed circuit is powered, opening the gate. Transistors also can be configured to be an electronically controlled switch and we can programmatically control the general purpose input/output pins of a raspberry pi to drive the transistor.

This gives us the following circuit:

Assembly

voila:

The software

Combined with the following bash script running on the raspberry pi 3:
#! /bin/sh

set -u

export WEBSOCKETEMAIL_TOKEN=$(cat websocketemail_token.txt)

# A secret id that people can't guess
gateid=gate12345

# initialize gpio
echo 13 > /sys/class/gpio/export
echo out > /sys/class/gpio/gpio13/direction

while true
do
  if wsemail -timeout 0 -for-address $gateid@websocket.email \
     | grep -q "open sesame"
  then
    # Trigger the gate if the email contained the secret incantation
    echo 1 > /sys/class/gpio/gpio13/value 
    sleep 0.1
    echo 0 > /sys/class/gpio/gpio13/value 
  fi
  # don't loop too fast if there is an error somewhere.
  sleep 1
done
The code can be summarized as: The code is MIT licensed on github.

The result


Step aside Amazon IOT, you are doing it wrong. Also, I know my email address is in the video, send me nice comments :)

Conclusion

Interacting with the real world using software is a lot of fun and I encourage you to have a try at building something for yourself. These days you do not need to be an expert in electronics to make something that interacts with the physical world. websocket.email also did it's job well, and I hope it can also be useful anywhere you need to interact with email accounts ... perhaps even unit/integration tests at your software job... wink wink.

Happy hacking!

FAQ

What do you mean 20 lines of code... There is go code in there!?

20 lines of shell needed to solve the task at hand, wsemail is reusable, just like your OS kernel, cat and all the other software it also used that you didn't complain about... though you aren't totally wrong.

Why you wouldn't you setup an smtp server on the device? Why add websocket crap?

NAT makes things annoying if you run the smtp server on the device, but I did setup an smtp server, and made a tiny api for it too :). Feel free to setup your own smtp server and use that instead.

Why you wouldn't you use IMAP to poll the server?

Which server? which account? Am I retaining emails? Sounds annoying. In my opinion the current configuration is a bit simpler for this use case.