This section describes how to configure alerts in pi_garage_alert.  If you haven’t already read part 1 of this series, please read it first.

Configuring Pi Garage Alert

  1. The configuration is stored in /usr/local/etc/pi_garage_alert_config.py. Go into the menu in the bottom left corner of the screen, and select “Leafpad” from the “Accessories” menu. An editor will appear. Pick Open from the File menu, select “File System” from Places on the left, then navigate to and open /usr/local/etc/pi_garage_alert_config.py.
  2. You’ll notice two garage doors are defined, but many lines describing the garage doors start with “#”. This indicates a comment line in Python and these lines are ignored by the compiler. So, the default configuration actually only defines one door on pin 15 called “Example Garage Door” with no alerts (all commented out).garage_config2
  3. The ‘pin’ line specifies which GPIO pin the magnetic sensor is connected to.
  4. If you have multiple garage doors, replace “Example Garage Door” with a description of which garage door the sensor is connected to.
  5. Each alert has three parameters
    1. state – what state triggers the alert, open or closed.  This almost always should be open.
    2. time – how many seconds the garage door must be in that state before the alert is triggered.
    3. recipients – who to notify
  6. Uncomment (remove the #) one of the alerts, and make yourself the recipient of the alert.  Make sure there isn’t a comma after the last recipient.  The recipients line should look similar to one of the following:
    'recipients': [ 'sms:+11112223333' ]
    'recipients': [ 'email:someone@example.com' ]
    'recipients': [ 'twitter_dm:twitter_user' ]
  7. Save the updated configuration file.
  8. Each type of alert – email, twitter, SMS – requires configuration.  Follow the below sections for the alert types you’re using:

Email

The RPi needs to be configured with an SMTP server.  These instructions will cover forwarding mail through GMail and assume mail will be sent from GMail.  The email can be sent to any address, so if you don’t have a GMail account, create a new account for your RPi.  If you aren’t using email alerts, you can skip this section.

These instructions are largely summarized from http://rtcamp.com/wordpress-nginx/tutorials/linux/ubuntu-postfix-gmail-smtp/.

  1. Run the following commands in an LXTerminal window to install the prerequisites:
    sudo apt-get install postfix mailutils libsasl2-2 ca-certificates libsasl2-modules
  2. When prompted, configure postfix as an Internet site, and give raspberrypi as the mail name.
  3. Open /etc/postfix/main.cf in an editor, remove any line beginning with “relayhost =”, then append the following lines to it:
    relayhost = [smtp.gmail.com]:587
    smtp_sasl_auth_enable = yes
    smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
    smtp_sasl_security_options = noanonymous
    smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt
    smtp_use_tls = yes
  4. Open /etc/postfix/sasl_passwd in an editor and fill it with the following. Replace username@gmail.com with your GMail address, and gmail_password with your GMail password.
    [smtp.gmail.com]:587 username@gmail.com:gmail_password
  5. Fix the permissions and update postfix config to use sasl_passwd
    sudo chmod 400 /etc/postfix/sasl_passwd
    sudo postmap /etc/postfix/sasl_passwd
  6. Reload postfix config
    sudo /etc/init.d/postfix reload
  7. Send yourself a test email.  Replace username@example.com with your email address.
    echo "test mail" | mail -s "test subject" username@example.com

Twitter

This sections describes how to set up pi_garage_alert.py to send Tweets.  If you’re not using Twitter alerts, you can skip this section.

  1. Create a twitter account for pi_garage_alert.py
  2. Follow the instructions on http://talkfast.org/2010/05/31/twitter-from-the-command-line-in-python-using-oauth/ to create a new Twitter application on the new account.  Once you’re done, you should have the following:
    1. Consumer key and secret
    2. Access key and secret
  3. Edit /usr/local/etc/pi_garage_alert_config.py and enter those keys in the twitter section.
  4. pi_garage_alert.py can only send direct messages to its followers, so make sure you’re following the Twitter account you created.

SMS

SMSs are sent through a paid service called Twilio.  At the time of writing, they charge $1 per month for a phone number, and $0.01 per SMS message.  If you’d prefer free options, you can skip this section and use email or Twitter instead.

Here’s how to setup SMS through Twilio:

  1. Sign up for a Twilio account and put some funds in your account.
  2. At the top of your Twilio dashboard, an account SID and auth token are listed.  You may need to click the lock to show the auth token.
  3. Edit /usr/local/etc/pi_garage_alert_config.py and copy the account SID into TWILIO_ACCOUNT, and the auth token into TWILIO_TOKEN.
  4. Copy your Twilio phone number into TWILIO_PHONE_NUMBER.

Finishing Up

At this point you’ve updated the configuration file and performed the steps in either the Email, Twitter, or SMS section above.  Let’s test it out and configure pi_garage_alert to run when the RPi is powered on.

  1. If pi_garage_alert.py is still running, press ctrl-c to stop it and return to the command prompt.
  2. Run pi_garage_alert.py again with the new configuration:
    sudo /usr/local/sbin/pi_garage_alert.py
  3. Move the magnet away from the sensor so pi_garage_alert reports the garage door is open.
  4. Wait for the number of seconds specified in the configuration file (default was 120 or 600 seconds – you may want to shorten this for debugging).
  5. You should receive an email/tweet/SMS indicating the garage door is open, then if you close it, you should receive another email/tweet/SMS.  If you did not receive the email/tweet/SMS, examine the output of pi_garage_alert.py for any error messages and review the instructions above.
  6. Press ctrl-c to stop pi_garage_alert.py again.  In LXTerminal, enter the following command so it runs whenever the RPi powers on:
    sudo update-rc.d pi_garage_alert defaults
  7. Try rebooting your RPi, then in an LXTerminal window, run the following command:
    tail -f /var/log/pi_garage_alert.log
  8. You should see the log messages from pi_garage_alert.py.  Press ctrl-c when you’re done. pi_garage_alert.py will continue running in the background.
  9. If you have an additional garage door to configure or want to configure additional alerts, you should do that now.

All that remains is physically mounting the magnetic sensor and the RPi.  Many magnetic sensors are designed to be mounted to the bottom of the garage door, but also work equally well on the top of the garage door.  This avoids having to drill into the garage floor.

2013-08-04 GarageSensorMounted 001

Magnetic sensor mounted to wooden header at top of garage door

2013-08-04 GarageRPiMounted 001

RPi in ABS Project Box. The magnetic sensors connect to a terminal block on the bottom of the case.

The keyboard, mouse, monitor, and USB hub are no longer needed.  Power, USB Wifi (or Ethernet), and the magnetic sensors (to GPIO and ground) are the only connections required at this point.

If you have any problems after mounting the RPi, you can check on its status remotely over ssh.  Follow the instructions to ssh in, then examine the /var/log/pi_garage_alert.log log file.

 
  • Alvin Ow

    Hi,

    My name is Alvin. I am a newbie and I like your garage door project very much! It’s really awesome! Everthing went smoothly & tested OK according to your Part 1 procedures.
    I am struck at the protion where I try to send myself an email via echo “test mail” | mail -s “test subject”. I keep getting the following message: -bash: syntax error near unexpected token ‘newline’.
    I really appreciate if you could provide me some suggestions / solutions.
    Hope to hear from you soon.
    Thanks & have a nice day!

    • Hi Alvin,

      Thanks for the feedback! Make sure you don’t include the angle brackets () in that command. It should look similar to:

      echo “test mail” | mail -s “test subject” somebody@example.com

      I’ll also update the post to be more clear.

      Rich

      • Alvin Ow

        Hi Rich,
        Happy to hear from you.
        I’ll try it and thank you for your time.
        Best Regards
        Alvin

        • Alvin Ow

          Hi Rich,

          Sorry for disturbing you.

          I fould out that your had made some amendments on your post.

          After sending the following command:-

          sudo postmap /etc/postfix/sasl_passwd.

          I received the following:-

          postmap: warning: inet_protocols: disabling IPv6 name/ddress support: Address family not suaported by protocol.

          postmap: warning: /etc/postfix/sasl_passwd, line 1: expected format: key whitespace value

          postmap: warning: /etc/postfix/sasl_passwd, line 2: expected format: key whitespace value
          It is normal?
          I still can’t receive any test email.

          • Hi Alvin,

            The IPv6 warning is normal, but the other two are not. Make sure you have the [smtp.gmail.com]:587 and user@gmail.com:password on the same line – sasl_passwd should only be one line long.

            Rich

  • Frank Burch

    Rich,

    What an awesome project! I’ve implemented it without any problem whatsoever. I did have one question though. Is there a way to set the alerts so that they only fire during a certain time period? For example, only alert if the gate is opened during the evening or weekend.

    • Frank,

      Happy to hear pi_garage_alert is working well for you. I think the easiest way is to use cron to stop the pi_garage_alert.py script in the morning, then restart it in the evening.

      You can stop pi_garage_alert from a terminal with “sudo service pi_garage_alert stop”, and start it again with “sudo service pi_garage_alert start”. So, a simple crontab (cron table) to stop the alerts at 8am and restart them at 5pm each day would look like:

      0 8 * * * sudo service pi_garage_alert stop
      0 17 * * * sudo service pi_garage_alert start

      http://v1.corenominal.org/howto-setup-a-crontab-file/ discusses the format of the file and has examples with more complicated schedules like running on specific days of the week.

      So, if you save those two lines to a file, you can run “crontab ” on your RPi to activate it (no quotes or angle brackets). I’d recommend also running the “date” command and ensuring the time and date it reports look correct.

      After a day or so, you can then check the /var/log/pi_garage_alert.log file to confirm it’s working correctly. You shouldn’t see any log entries between 8am and 5pm in this example.

      Rich

  • Tom

    Rich, Thanks for setting this up, works great, I have a 2 bay detached garage and another on my house. I have it in testing setup for all three now. a question I have is are you planning on adding the ability to operate the doors using the GPIO and relays to activate the switches? I’ve seen other projects where they have mobile apps too. I’m not a programmer or developer so I’m not sure how it could be done.
    Any suggestions or thought?

    • Tom,

      From the hardware side, I imagine a transistor, perhaps a 2N7000, and a relay connected to the existing garage door button would allow you to operate the door. I’d suggest also checking out the SainSmart relays for Arduino – reportedly they work fine with the RPi and are inexpensive.

      On the software side, I think the simplest solution would involve running a web server on the RPi and having a web page control the garage door. A simple CGI script could momentarily trigger the relay (check out wiringPi’s gpio program). The script could also query GPIO to get the garage door state. Security would need to be carefully configured.

      Home users would also need to configure port forwarding (open a port) on their router as well configure a dynamic DNS service (so they can find the RPi on the internet).

      I’d like to keep this project simple and accessible, so I’m not planning on adding the ability to operate the doors. However, like you mentioned, there are other projects that do and you likely could run both this project and the other ones in parallel if you wanted to get the best of both worlds.

      Rich

  • Glenn

    Rich, thanks for all the work documenting this! It encouraged me to practice some python, PHP, and learn about twillio. I have this setup on my garage now, and modified it so that i can SMS the twillio number and query the state of the door. I cheated and just have twillio return the last line of the /var/log/pi_garage_alert.log file. It returns a lot of extra data the script outputs to the log every 10 mins. Is there a way to call your python script and return the state of the door rather than parsing out the state from the last line of the log?

    • Well, this may not be the cleanest solution, but if you make a copy of pi_garage_alert.py and replace the main() function with something like the following, it’ll just print the current state to stdout. You could then call this script whenever you get a query.


      def main():
      GPIO.setmode(GPIO.BOARD)
      for door in cfg.GARAGE_DOORS:
      GPIO.setup(door['pin'], GPIO.IN, pull_up_down = GPIO.PUD_UP)
      door_states = {}
      for door in cfg.GARAGE_DOORS:
      name = door['name']
      door_states[name] = name + ": " + get_garage_door_state(door['pin'])
      print(' / '.join(door_states.values()))
      GPIO.cleanup()

  • Jaa5

    Rich, great job on this! Love this concept. I have it all setup and working with SMS via twilio, but no joy using gmail. “class ‘smtplib.SMTPSenderRefused’ STARTTLS….” . I need to email because I added a camera to the RPi to snap photos shortly after the door is sensed OPEN. Thanks for taking the time to write this up! Huge help!

    • Jaa5, sounds like the SMTP server doesn’t like your “From:” email address. Is your SMTP_SERVER in pi_garage_alert_config.py set to localhost or smtp.gmail.com?

  • Jaa5

    Thanks, the test mail works fine (echo “test mail” | mail -s “test subject” username@example.com), just not working from your python script for some reason. I tried several things in the postfix/main.cf, still no luck. same error . any ideas?

    • Is your SMTP_SERVER in pi_garage_alert_config.py set to localhost? If so, I’d suggest reading through the mail server logs in /var/log and look for an indication why it’s refusing the email.

  • Jaa5

    hey Richard, I noticed on github you updated your code. Does this take care of failures when trying to send text or Gmail? thanks for a great project and write up!

    • Yes, if the RPi’s internet connection is down when it wants to text/email, it’ll now log the error and keep running.

      • Jaa5

        Super! Thanks Richard

  • AndyZ

    Hi – this is really great. Thanks for taking the time to share it with us. I notice the magnetic sensor is hard wired. Is there any chance you can kick me in the right direction for exploring a setup for multiple doors with wireless sensors? Is that extra GPIO pins and Xbee communications, or is there another way?

    • XBee series 1 have “I/O Line Passing” that essentially create a virtual wire between the transmitter and receiver. The wiring and configuration are fairly simple. I attached a rough schematic of how you’d wire it. You then configure the transmitter to periodically sample DIO0 and enable sleep to conserve the battery. The receiver gets configured with the IA parameter as the address of the transmitter and DIO0 as an output. The product manual has the full details. Definitely test it out with an LED before trying with the RPi and making the whole system work.

      I’ve done this sort of thing before with one XBee transmitter and one XBee receiver. If you need more XBee transmitters for the multiple doors, I’d check the datasheet and manual to see what your options are there.

      • AndyZ

        Outstanding! Thanks for the detailed guidance.

  • DeVaughn Barnum

    I have my pi also enabling control of the doors via a relay with a web interface. Is there a way to have your alert include the web url with the door status? Thereby allowing me to open the website right from the email?

    • DeVaughn,

      Sure, you can edit /usr/local/sbin/pi_garage_alert.py and look for these two lines:


      send_alerts(recipients, name, "%s is now %s" % (name, state))
      ...
      send_alerts(alert['recipients'], name, "%s has been %s for %d seconds!" % (name, state, time_in_state))

      If you insert your URL between the double quotes and then do a “sudo /etc/init.d/pi_garage_alert restart” from the terminal, your URL will be in the emails.

      Rich

      • DeVaughn Barnum

        Thank you Richard, I’ll give that a shot.

  • Andrew

    Hi Richard,

    Love the program, but, the SD card that was running it seemed to die a few weeks ago. I’m really not sure what happened, but, it looks like I may have run out of disk space. Before I spend any time getting my pi up and running again, I was hoping you could tell me if there is any mechanism built in to roll the log file. Looks like its just writing to stdout, so I’m guessing there’s not. If there isn’t, I think I’ll take the easy way out and write a cron job to truncate the log once a day, just to make sure I’m not running out of space.

    Thanks.

    • Linux has a utility called logrotate (http://linuxcommand.org/man_pages/logrotate8.html ) that’ll do that for you. It should already be installed on your RPi. pi_garage_alert logs to /var/log/pi_garage_alert.log. However, I’ve been running mine for several months and pi_garage_alert.log is only up to 5MB so far. At that rate, it’ll take centuries to fill up even a small SD card.

      • Andrew

        Some additional debugging showed that the SD card was completely corrupt, so the original signs that it was disk space were just misleading. think I’ll still roll the logs anyway.

        Thanks.

  • Michael

    Richard, this is fantastic! One question: rather than having the Twitter portion send a DM, could it be modified to just send a regular tweet? I have set up a private twitter account that I can follow, so no one will be able to see the tweets unless I give them access. I’d like to be able to see the tweets on the accounts I’ve authorized to follow the garage door tweeting account. I hope that makes sense. Thank you again!

    • Michael, sure, I just checked in the changes to have it send regular tweets. If you grab the latest version of pi_garage_alert.py from Github, instead of using recipient “twitter_dm:username_here”, you can specify recipient ‘tweet’.

      • Michael

        Thank you Richard! I really appreciate it!

  • Rick

    Is it possible to connect with the Raspberry Pi through a web browser? Since it has wifi, it seems like I should be able to locate the device on my home network and make changes to the configuration through a web browser? Otherwise, do I need to pull the device out of my garage and connect it to my computer to make changes?

  • Jay Curcillo

    To access a Gmail account protected by 2-factor verification in Mail,
    you need to make sure your Google account recognizes your phone as an
    authorized device. To do this, go to your two-step verification page:

    https://accounts.google.com/b/0/SmsAuthConfig

    and click “Manage application-specific passwords.”

    Then enter the password given in the mail app. You may have to delete and reset your mail account. This worked for me.

  • Alex

    I’m new to pi and this will be my first project. Is there a way to get the program to send a sms/email/tweet every X seconds until closed after an initial waiting period?

    • If you modify the code you could get periodic alerts. Look for the second call to send_alerts around line 578 of pi_garage_alert.py. There’s an ‘if’ condition above it that you’d want to make true, perhaps by resetting time_in_state to 0.

  • YDG

    Hi Rich, apologies for asking for help on tweepy but I’m having issues authorising my app based on the linked instructions.

    I get part way through step 3. I enter the pin, but receive an error

    pi@raspberrypi ~ $ sudo /home/pi/tweepy/rd.py

    Please authorize: https://api.twitter.com/oauth/authorize?oauth_token=*****
    PIN: *****
    Traceback (most recent call last):
    File “/home/pi/tweepy/rd.py”, line 14, in
    print “ACCESS_KEY = ‘%s'” % auth.access_token.key
    AttributeError: ‘unicode’ object has no attribute ‘key’

    I’ve tried renaming the script and my app as I read this may be an issue. I’ve also adjusted a few things within the script but I’m a noobie with all of this.

    PS – I wanted a garage door reminder since losing some power tools from my garage. Your work inspired me to get a pi and learn something. Cheers!

    • Looks like the Tweepy API changed a little bit in in April. If you replace auth.access_token.key with auth.access_token, and auth.access_token.secret with auth.access_token_secret in the rd.py script, rd.py should work with the new API.

      • YDG

        That’s it. Thanks so much for your help!

  • Patrick

    noob to Linux, in step 4 of email you say to ‘Open /etc/postfix/sasl_passwd ‘, however, that file does not exist and must be created, however, I cannot get the OS to let me create the file due to being denied (permissions), how can I get around this and create the file?

    • Patrick

      I worked my way around creating the file, but should I have had to create a new file, or should there have been one there to edit? Testing email results in no email being received, is there a log that I can review to see what’s going on?

      After going through all of the setups(I successfully ran pi_garage_alert and tested with my hardware, but at the end of everything I attempt to run pi_garage_alert and it fails with the following:

      Traceback (most recent call last):
      File “usr/local/sbin/pi_garage_alert.py”, line 59, in
      import pi_garage_alert_config as cfg
      File “/usr/local/etc/pi_garage_alert_config.py”, line 45
      LOG_FILENAME = “/var/log/pi_garage_alert.log”
      SyntaxError: invalid syntax

      • It’s normal to have to create sasl_passwd. For the syntax error, double check your GARAGE_DOORS in pi_garage_alert_config.py and make sure every { is paired with a }, and every [ is paired with a ]. All the lines starting with # can be ignored.

        • Patrick

          Richard,

          Thank you, that was it, I had left a few extra } and ] commented out. I have Twilio working, texts send with no issues. I cannot get email to work though. If I do the command line test the emails work, but if it is an Alert I receive the text but no emails and it fails with, “2014-08-11 23:49:23, 943 ERROR Exception sending email:

          I have checked my Postfix configuration and figure that must be correct or the test emails would not work. My thought is that it is something within the pi_garage_alert_config.py but I have checked through the documentation and it over and over but I must be missing something.

          Thank you again for the great program and your helpfulness.

          Sincerely,
          Patrick

          • That indicates postfix doesn’t like the From: address you specified in EMAIL_FROM in pi_garage_alert_config.py, e.g. it’s missing the domain name or it’s invalid in some way. The following log files may also give some further clues what’s wrong. I’d recreate that error then look at the last few lines of these files:

            /var/log/mail.log
            /var/log/mail.info
            /var/log/mail.err
            /var/log/syslog

          • Patrick

            Thank you,

            I checked the logs, mail.log and mail.info just show the IPV6 isn’t supported disabling etc. mail.err is empty, no entries. syslog shows the ipv6 errors and that is all.

            Looking at pi_garage_alert_configy.py the Email Settings are,

            SMTP_SERVER = ‘smtp.gmail.com’
            SMTP_PORT = 587
            EMAIL_FROM = ‘Garage Door ‘

            I will keep looking.

            Thanks again,
            Patrick

          • You probably can’t use Google’s SMTP server without adding code to pi_garage_alert.py to authenticate with it. Try using the mail server on your RPi, so SMTP_SERVER=’localhost’ instead. It’ll then relay the mail to Google.

          • Patrick

            Richard,

            You ROCK!!! That was it, I changed to ‘localhost’ and needed to change the port back ’25’. and I am not able to send alert emails at will. I am 100% working, thank you SO much!

            Patrick

  • Chris K

    Got this going and really like it. Get article. I’m interested in trying out the Jabber notifications. I see that it is setup but am unsure how to configure. Can you elaborate?

    • Sure, you’d want two Jabber accounts – one will send notifications and one will receive the notifications. If you have Google accounts, they work well here since Google Talk works over Jabber. Jabber.org also runs a free server. You may need to have the two accounts friend each other (depending on the server).

      Configure JABBER_ID and JABBER_PASSWORD in pi_garage_alert.py with the credentials for the account that will send the notifications.

      Sign into the other Jabber account on your smartphone/computer/etc, and add that ID to the notification list in pi_garage_alert_config.py. It should look like jabber:username@domain.com

      You can optionally also add that account to JABBER_AUTHORIZED_IDS in pi_garage_alert_config.py. This will allow you to send IMs to pi_garage_alert and have it respond with its status. Currently, the only supported command is ‘status’.

      Once it’s configured, stop any background instances of pi_garage_alert by running “sudo /etc/init.d/pi_garage_alert stop” on the RPi, then start it up again with the new config, “sudo /usr/local/sbin/pi_garage_alert.py”. If everything goes well, it’ll print out “JID set to: ” followed by the Jabber ID it’ll use to send IMs. You should also see its IM status go to ‘online’ from your smartphone/computer.

  • Loral Godfrey

    Is step 6.

    cat /etc/ssl/certs/Thawte_Premium_Server_CA.pem | sudo tee -a /etc/postfix/cacert.pem

    supposed to be entered in as two lines or one?

    • Sorry for the slow response. It should be entered as one line.

      Rich

      • Loral Godfrey

        Not a problem, I realize the article is getting older. Thanks for letting me know!

  • Jas Harrar

    Hi,

    This worked for me, although I had some issues with ipv6 errors but it worked anyway also got an email from Google that required some chenges to Gmail settings so the pi could use it. Would it be possible to get the pi to take an image and send it to me? If so how would I do.this? great guide many thanks

  • WickedBe90

    Don’t know if you still check this at all.. but I’m receiving an error when trying to send email… test emails work… but with the script I get “ERROR Exception sending email: .. .Any ideas? Thanks.

  • Woki Home

    how to make it work for Raspberry Pi 2 Model B please

    • Pretty much the same process except you need to buy a micro SD card instead of full size SD, and there will be more pins on the GPIO header. The physical form factor will be different so make sure the case you buy is compatible with the Raspberry Pi 2 model B.

      The GPIO pinout is at http://elinux.org/RPi_Low-level_peripherals#Model_A.2B.2C_B.2B_and_B2 . The layout of the top 26 pins is unchanged from the Raspberry Pi 1 A and B, so if you ignore the 14 new pins, the wiring instructions are unchanged.

      • Woki Home

        that is Great, Richard

  • Spiffy Doo

    Rich, any clue what this might mean?

    pi@pi-garage1 / $ sudo update-rc.d pi_garage_alert defaults
    update-rc.d: using dependency based boot sequencing
    insserv: script pi_garage_alert is not an executable regular file, skipped!

    • It means /etc/init.d/pi_garage_alert is somehow not executable. Try manually setting the excutable bit with chmod +x /etc/init.d/pi_garage_alert.

  • Kristofejro

    Hi Rich,

    I am using SSMTP on my Raspberry PI and send test message:

    echo “test mail” | mail -s “test subject” username@example.com

    works fine but when script tries to send email it generates error:

    2015-10-10 10:12:49,068 INFO Sending email to mail@domain.com: subject = “Door”, message = “Door open for 3 seconds!”
    2015-10-10 10:12:49,164 ERROR Exception sending email:

    All data in in config.py has been filled out:

    SMTP_SERVER = ‘smtp.gmail.com’
    SMTP_PORT = 587
    SMTP_USER = ‘myemail@gmail.com’
    SMTP_PASS = ‘mypassword’
    EMAIL_FROM = ‘myemail@gmail.com’
    ‘recipients’: [ ‘mydestinationmail@domain.com’ ]

    Do you know what the problem it may be?

    • If you want to directly connect to Gmail’s SMTP server over TLS, you’ll need to add a couple lines to pi_garage_alert.py to enable TLS. Around line 353, you’ll see a line “mail = smtplib.SMTP(cfg.SMTP_SERVER, cfg.SMTP_PORT)”. Right after that line, add these two lines. Note, there needs to be exactly 12 spaces at the beginning of each line, otherwise Python will complain.

      mail.ehlo()
      mail.starttls()

      You should then be able to use that Gmail configuration.

      • Kristofejro

        You are the man Rich 🙂
        Thanks for quick help.
        It works like a charm now.
        Your scripts are the best!

  • Kristofejro

    Hi Rich,

    oYour script was warking just fine until now.
    I started to get log full with:
    ERROR Exception sending email:
    when script tries to send email.

    Sending emails from my Pi works fine which was tested.

    Do you have a clue where is the problem?

    • The SMTP (mail) server is rejecting your mail for some reason. Is SMTP_SERVER in pi_garage_alert_config.py set to something other than localhost?

      • Kristofejro

        Thanks for quick answer and sorry to bother you.
        I have upgraded to Jessie and and probably it messed with permissions.
        I just managed to fix the problem and it works like it should (and used to)

        Thanks again.

  • jay six

    is it possible to restart the /usr/local/sbin/pi_garage_alert.py without reboot?. I’m having having small issue. the pi_garage_alert.py will stop notifying me after a few days of running (after a week or so). The only solution is to reboot the whole unit (Pi). I know the unit it self it not freezing because i can still access it via ssh and also log into my sprinkler program (SIP) and run the program without any problem. when the pi_garage_alert.py stopped and i reboot the Pi, I get a whole bunch of notification right after. Seems like pi_garage_alert.py will stopped and accumulate all the notification and send it at once after reboot. Im thinking memory issue? maybe restarting the program every 3 days would be a good work around?

    • You could do a “sudo service pi_garage_alert restart” to stop and restart it, but pi_garage_alert doesn’t queue notifications through restarts, so most likely the cause is something else.

      Are you using email notifications or something else? Postfix (email server) will queue things up if there’s a problem, so perhaps you need to restart it? I’d also suggest checking out the logs in /var/log to see if they offer any clues.

  • Rich Strle

    Hi, I’m having trouble sending emails. I can’t find the cacert.pem file in the /etc/postfix directory. I ran the sudo apt-get install postfix mailutils libsasl2-2 ca-certificates libsasl2-modules again and it says everything is the latest version 0 upgraded, 0 newly installed, 0 to remove and 1 not upgraded. I did a find . cacert.pem and got ‘No such file or directory.’ I’m out of ideas.

    • It’s created in email step 6 with:

      cat /etc/ssl/certs/Thawte_Premium_Server_CA.pem | sudo tee -a /etc/postfix/cacert.pem

      • Rich Strle

        Thanks, that fixed that problem. I’ll start a new item for my next issue.

  • Geoff R Galley

    I have been searching the net for a garage door notifier and came across
    yours. So I ordered the equipment but I ordered a Pi2 B+ instead to
    furture proof myself.
    I was following your instruction right up to
    the part when you enter in the email details Ie SMTP server editing the
    Main.cf. Once I enter in all the details and try to save it I get an
    error message stating it’s unable to open main.cf to save.
    So at first I thought I was doing something wrong So I started all over again, to find out I hit the same speed bump.
    I also found that when installing the prerequisites, when entering the following commands “sudo pip install requests”, “sudo pip install requests[security]” I get a message stating to 0=upgrade.
    Also these file doesn’t seem to exist either /etc/postfix/sasl_passwd.

    I could be doing something wrong but I can’t seem to figure out what.

    I am using the latest Raspbian

    Geoff

    • For the issue related to editing main.cf, you’ll need superuser privileges to edit it, so prepend “sudo” to your editor command (e.g. sudo nano main.cf).

      It is normal that /etc/postfix/sasl_passwd doesn’t exist yet – you’ll need to create it and populate it with the gmail credentials.

  • Nicolas Pilet

    I just want to say a big thanks. I am using you scripts in order to have a river level detector which inform me when my garden is at risks of flooding. Your explanations are very useful to me. Many many thanks 🙂

  • Gerald Essenberg

    Really good article! I was not able to get the SMTP part to work with my own ISP. I get an invalid HELO name error message and everything points back to bad SMTP config (no SMTP server authentication?). Which file needs to be properly configured and how does the correction look like?
    Thanks 😉

    • If you’ve already filled in SMTP_USER and SMTP_PASS in pi_garage_alert_config.py with your credentials, you might need to modify pi_garage_alert.py around line 354, right after the “mail = smtplib.SMTP(…” line. Add a line reading “mail.ehlo()” followed by “mail.starttls()”. This will enable TLS (encryption) which may be required by your ISP’s mail server.

      • Gerald Essenberg

        Richard, I am all set. I love it! It is all fixed and runs like a charm.
        Just one final question:
        I see that the program displays a CPU and GPU temp status every 10 minutes.
        What can I do with that? I am going to use the RPI as a stand alone device and won’t see any screens. How can I use that info to be pushed e.g. as an alarm if it exceeds a certain temp to the same email address?

  • Nicolas Pilet

    Hello Richard. Like I mentioned below everything was working after installation. However after rebooting the RPi, email sending is not working anymore. Only when running ”sudo apt-get remove postfix mailutils libsasl2-2 ca-certificates libsasl2-modules” and then ”sudo apt-get install postfix mailutils libsasl2-2 ca-certificates libsasl2-modules” again things start to work again. When doing so the email generated before the re-installation are also sent. Any idea why emails are not sent?

    I don’t know if it is related but the step ”cat /etc/ssl/certs/Thawte_Premium_Server_CA.pem | sudo tee -a /etc/postfix/cacert.pem” which is mentioned only in the discussion (it does not appear in step 6) returns an error in my case: ”cat: /etc/ssl/certs/Thawte_Premium_Server_CA.pem; No such file or directory”

    Any idea how to debug that? Many thanks in advance.

    • Recently Raspbian stopped including that Thawte certificate, so I updated the instructions to use the /etc/ssl/certs/ca-certificates.crt certificate bundle instead. I’d suggest double checking that your /etc/postfix/main.cf matches the instructions on this page, then if the problem persists, try sending an email from the Raspberry Pi, then look at /var/log/syslog (e.g. “tail -50 /var/log/syslog” from a terminal). The log messages should give some clues why the mail is not being delivered.

      • Nicolas Pilet

        Another issue is the command “sudo update-rc.d pi_garage_alert defaults” does not seems to start garage_alerts during the boot. Can that be related? Anyway even after using the command, garage_alerts is not running and “tail -f /var/log/pi_garage_alert.log” returns “tail: cannot open ‘/var/log/pi_garage_alert.log’ for reading: No such file or directory
        tail: no files remaining”. Indeed the mentioned file is not there.

  • Gerald Essenberg

    The script uses the names “open” and “closed” to indicate the garage door to be open or closed. How can I customize it to say something is powered or without power, or somehting completely different?
    I tried to change the replace the open and closed words with what I want, but generates problems. Thanks!

    • You just need to replace open and closed with the new words in both pi_garage_alert.py and pi_garage_alert_config. Make sure you don’t disturb the whitespace at the beginning of lines and don’t modify the “with open” line in get_uptime or get_gpu_temp.

      • Gerald Essenberg

        Thanks Richard, it works !
        You are amazing. Not only your “product” is the best, your service is just as great! Your one of a kind. Thanks buddy!

  • I’ve never seen that behavior myself but it seems to affect some Ubuntu/Debian users as well. I’d suggest Googling the warning message about resolv.conf and trying some of the fixes others have used.

    • Michael Zhang

      I have having exactly the same issue.
      HW: RPi 3B.
      SW: Debian (latest)

      After all the procedure listed here, I was able to send test email once. After waiting for a long time (~30 min) , I was able to send the test message again. I just want to make sure the process is recursive. Pretty happy about that, but after reboot, the email / txt doesn’t work anymore. Looking at /var/log/mail.log, the first 2 times are with the correct relayhost, but after reboot, the relay=none. Try to uninstall packages, and reinstall, but the uninstall is not successful due to some strange message (maybe shared resource). Now I am looking for a solution.

      • Michael Chang

        Thanks Nicolas for the workaround. Tried it, and it worked. After thinking more about other thread I heard, and googled about the error message per Richard’s suggestion, I found out it is a timing thing when one of the email conf was copied at earlier stage. After enable PI “wait for networking” config at top level PI config menu, I can power down the PI and power up and send test email right away without the workaround.

        BTW, Richard: Thanks a ton for the detailed instruction and Python code, it really helps me in getting the garage project started quickly. Learned a few things along the way.

  • Zehn

    Great program works great but my log file don’t write and I don’t get any errors and I changed the config file to save log file on desktop /home/pi/Desktop/…..

    but no luck with that i am kinda new to linux i assume some folder permissions may be the issue???

  • GregP

    I was having problems with email not sending with my Pi 2 Model B using a WiFi USB Dongle. Solution was to go into Preferences -> Raspberry Pi Configuration -> System and set Network at Boot: to “Wait for network”.

  • Anthony M

    I tried this on my Pi 3 but using the Pushbullet feature that was in the config file. I put my access_token in the proper place, and the pi shows that it’s making the connection to pushbullet.com and attempting to send the status note, but it never sends the message. I don’t get any authentication errors, and the log shows it attempts to connect and send, but it never does complete and/or actually send, . I know this is an old post, but any thoughts?

    edit: if you’re wondering why I want to use Pushbullet, it’s because it can send the notification to all my devices at once.

  • Anthony M

    Thanks again for the hard work on this program! This is exactly what I’ve been looking for, and seems a great place to start learning more about Pis and scripting. However I’m running into an issue and I hope someone can help out. I know this is an old thread but I hope folks still look at it. I followed all instructions and everything seems to be working great. I’m trying to use the Pushbullet functionality that seems to be built into the script, but I’m running into problems. I want to use Pushbullet because it will send the notice to all my devices at once, very convenient! Anyhow, I added my access_token to the config and when I launch the script, everything appears to be functioning as intended: the door state being open for X seconds gets triggered and the logger shows that the script is going to send the Pushbullet note to my access_token. The logger then shows that it’s starting a new HTTPS connection with the Pushbullet api url (api.pushbullet.com). It’s at this point that i’m not sure where the problem is. The push never gets sent, and the logger shows no other info (no bad authentication, no timeouts, nothing). Is it possible that pushbullet has changed the way their API works since the time this script was written? Looking briefly at the way Pushbullet’s API works, it uses curl. Being that i’m not exactly a script person, has anyone built something for this that works? I couldn’t find anything similar via Google. Anyone else have luck getting this script to work with Pushbullet as is or with slight modification? Thanks!

    • I just tried it with Pushbullet and it worked for me. I’d suggest trying with curl first to make sure your API key is working correctly. This command should post a push. Make sure you replace the api_key with your key:

      curl -u api_key: -X POST https://api.pushbullet.com/v2/pushes –header ‘Content-Type: application/json’ –data-binary ‘{“type”: “note”, “title”: “Note Title”, “body”: “Note Body”}’

      • Anthony M

        Thanks for the reply. It seems like my key just wasn’t working. I revoked the old key, issued a new key and everything is great now. I did have End-to-End encryption enabled on my Pushbullet account, so I’m unsure if that was causing the issue, but either way it works fine now. Thanks again for your help, and it’s pretty awesome that you’re keeping this old thread alive!

  • sasl_passwd won’t exist yet – it’s a file you create.

    • Doug N

      Ok. Any particular file type? With particular permissions? Thanks.

  • Pepper

    Hi, can you help my? have this message on $ sudo 2016-05-21 11:02:46,611 ERROR Exception sending email:” nobody can help, as appreciate 🙂 Thx..

  • Benjamin Piraro

    would like to see this script run as a non-root user…. simply to eliminate any security threats/vulnerabiities.

  • Derin

    A good way to send texts is to utilize email to sms gateway, and use personal email service like gmail as the smtp.

    I have my Linux NAS send me alerts using this, works great. I attached all the carriers emails. Just add your phone number and good to go.

    No need to pay for a silly service!

  • Derin

    Also thanks for the hard work on this, just picked up a pi zero and going to try this out this weekend!

  • Benjamin Piraro

    So have had this up and running for close to a month now, works great, but would like to know if it is possible (or if there is an option available) to have the total time the garage was open to be included in the “NOW CLOSE” message that is sent to me via email/sms?

    I randomly get this info sent to me if the garage is open and the RPi is powered off and then you close the garage. The program seems to notice the door is now closed and sends an email with total time.

  • jay six

    Hi Richard.. is it possible to add a reminder notification. i know you can set the timer to send you a notication how long the door is been open. but is it possible for the reminder to have different subject and message…

    for example “garage door open 1 sec ago”, second reminder would be “the garage door has been open for x amount of minutes”

  • Tim

    Thanks for this article. This was my first raspberry pi project and I got it working last weekend. I got twitter to work fairly easily but couldn’t get gmail to work.

    I played around with the email settings tonight and got it to work. I thought I’d add a comment in case someone else runs into the same socket error issues that I had.

    After debugging the code, I found the line “mail = smtplib.SMTP(cfg.SMPT_SERVER, cfg.SMTP_PORT)” was causing the issues. The parameters in the config file were correct, but it kept giving me a socket error. I tried hardcoding the line with the gmail info and I got the line to work. I used this instead: “mail = smtplib.SMTP(“smtp.gmail.com”, 587)”

    I also added these two lines after that line: “mail.ehlo()” and “mail.starttls()”.

    When I ran it with those changes I got an authentication error, but after checking the sending account’s email, there was an email from Google saying something tried to access the account. I had to change an option to allow less secure apps. After doing that, it worked.

    Thanks again for all of your work that went into this. This was a great learning experience and I’m excited to get my next RPi and start another project.

  • RS

    Hi,
    Great tutorial! I have SMS working. The email setup will not work with Gmail if you have two-step verification.
    Here is the fix:
    http://passion4high-tech.blogspot.com/2013/03/postfix-sasl-authentication-failed-with.html

  • RC123

    I had a free trial Twilio account and I was getting SMS text messages to my cell phone. I don’t want to pay for a Twilio account and my free trial account is over so I set things up to send the notification to my Twitter account and it’s working fine, I receive a message in my Twitter account when the garage door has been left open. How can I get the message to my cell phone as a text message? Is there a way to “follow” my Twitter app? Is there a way to set a “notification” on my Twitter account when I get a message from my Twitter app? Thanks for any advice you can offer.

  • George Williams

    Great article – could you substitute an IFTTT trigger for your email, SMS or Twitter. This would let you do all sorts of things based on the trigger action of the door opening. Perhaps turning on the garage lights when OPEN triggered. With apilio.io you could also combine the status of 2 doors (if either OPEN turn on lights – if both CLOSED turn off lights. The trigger is simply a post http IFTTT maker channel. I suppose it would just be a case of popping this into your code in place of the email/SMS/Twitter trigger.

    • Good idea – I’ve added IFTTT support using IFTTT’s maker channel. If you take the key from https://ifttt.com/services/maker/settings (the end of the URL on the page), and put it in IFTTT_KEY in the new config file, you can then specify recipients in the config file like ‘ifft:garage_event’ to trigger IFTTT applets. The extra data value1, value2, and value3 will be filled in with the garage door name, open/closed state, and time in that state.

      • George Williams

        Thanks but having run my version for a day, I’ve found the triggers through IFTTT have become incredibly unreliable. Sometimes the IFTTT trigger fires but the output doesn’t or the trigger fails to fire at all.

        I have downloaded a Telegram client (think opensource WhatsApp) for my Pi and I post directly to that. I adapted some of your script with a fridge door monitor script I found elsewhere and added some functionality to cover 2 doors such that the alarm works with either door open or both (in terms of the alarm timer beginning to count up).

  • W HORNER

    hi Richard,
    New to all this. running on a RPi 3B. I believe I followed all the software step by step installation instructions. The requests[security] install fails (Screen shot 1 (sorry for the rotated image)) When I try to run the application it errors out looking for “oauthlib.common” (Screen shot 2). I must be missing something in the installation but don’t know enough yet to figure it out. Any help would be greatly appreciated. https://uploads.disquscdn.com/images/86d30c44854940f382e69bf084005aaccb24f0dee0c19ad7988835fa4ef528d5.jpg
    https://uploads.disquscdn.com/images/a42598d6a7a1b69c54bb7a3a3f0cc71bae417baa6170eddb115c449aa833d5ac.jpg

    • It looks like the Twilio 6.0 Python package and some of its dependencies cause problems for Raspbian. I’ve updated the part 1 post with a fix from another commenter. I think if you issue the following command, it should get your Python/pip back into a good state:

      sudo pip install -U twilio==5.6.0 oauthlib

      Rich

      • W HORNER

        Thanks for the help Rich that fixed it.

  • Rick

    Is it possible to substitute Orange Pi for Raspberry Pi?

    http://www.orangepi.org/orangepipc/

    • I don’t have one so I can’t try, but from Googling around, it sounds like you’d at least need to use a different Python GPIO library. So, there’d probably be some extra steps.

  • Rick Dunn

    I was hoping to use this on a schedule … like 9PM – 6AM however I wasn’t sure how cron would shut it down without a kill command… Will this mess up the GPIO settings? Also would like to add the ability to use a relay and shut the door automatically during the scheduled times

    • Rick Dunn

      realized this is installed as a service.