Sunday 26 October 2014

Switching appliances ON and OFF remotely by e-mail with the Raspberry Pi and Mains Switch Widget #2

Switching appliances ON and OFF using e-mails. This part of this multi-part post looks at logging in and reading e-mails from a gmail account and using the subject field to switch an appliance ON and OFF.

The code for doing this is presented below. It uses IMAP to log in and check the e-mails in the in-box. If the subject field is APP1ON then the appliance is switched ON. If the subject field is APP1OFF then the appliance is switched OFF.

Remember to set up a gmail account for this and enter the user name and password in the line starting with M.login. 

When the program starts, it sets the appliance to OFF, and then checks the in-box. The number of this e-mail is saved in variable "lastmail". The in-box is checked every 10 seconds and no action is taken if there are no new e-mails. (Some familiarity with python is assumed for understanding the code). For information on how to extract e-mails using Imap have a lok at this link below. All I have done is adopt the code here and worked out how to extract the subject field. http://www.voidynullness.net/blog/2013/07/25/gmail-email-with-python-via-imap/

Click here to download code from www.sf-innovations.co.uk website

Program listing starts

#!/usr/bin/env python
#program inspects e-mails and switches appliances ON and OFF
#Uses Mains SWitch Widget from www.sf-innovations.co.uk

import sys
import imaplib
import email
import datetime
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)

M = imaplib.IMAP4_SSL('imap.gmail.com')
APP1=11 # GPIO pin with Mains Widget connected
GPIO.setup(APP1, GPIO.OUT) #Set pin as output
GPIO.output(APP1, GPIO.LOW) #Always set to false at start

#Function for checking e-mails using IMAP
def process_mailbox(M):
  global text 
  rv, data = M.search(None, currmail)
  if rv != 'OK':
      print "No messages found!"
      return

  for num in data[0].split():
      rv, data = M.fetch(num, '(RFC822)')
      if rv != 'OK':
          print "ERROR getting message", num
          return

      msg = email.message_from_string(data[0][1])
      print 'Message %s: %s' % (num, msg['Subject'])
      text = msg['Subject']
      print 'Raw Date:', msg['Date']
      date_tuple = email.utils.parsedate_tz(msg['Date'])
      if date_tuple:
          local_date = datetime.datetime.fromtimestamp(
              email.utils.mktime_tz(date_tuple))
          print "Local Date:", \
              local_date.strftime("%a, %d %b %Y %H:%M:%S")
    

#Start program and check last e-mail in folder
M.login('insert e-mail address@gmail.com' , 'insert-password!')
rv, data = M.select()
if rv == 'OK':
    lastmail= data [0]
    print lastmail
    M.close()

#Repeat this loop every 10 seconds
while True:
    rv, data = M.select()
    currmail= data [0]
    if currmail != lastmail: # Process if new e-mail received
        #print "read subject"
        process_mailbox(M)
        lastmail=currmail
        if text == "APP1ON":
            print "appliance 1 switched ON"
            GPIO.output(APP1, True)
        if text == "APP1OFF":
            print "appliance 1 switched OFF"
            GPIO.output(APP1, False)
    time.sleep (10)
    M.close()
M.logout()

End of program listing

Summary

This post looked at how to use an e-mail to switch appliances ON and OFF using the Raspberry Pi and a Mains SWitch Widget. In the next post, we will look at how to send a confirmation e-mail once the appliance has been switched ON or OFF.

To keep upto date with our blog posts, subscibe using the link provided on the www.sf-innovations.co.uk website.


No comments:

Post a Comment