Calendar-highresI’ve been doing a lot of work on my home automation system during the Christmas break. As part of that work, I have decided to break apart certain pieces of the “controller” (written in Python and running on a stack of Raspberry Pi’s) and share the code with everyone that might be looking for a place to get started doing something similar. I’m not going to share the code in its entirety, but I will be sharing bits and pieces of it that I have rewritten to be ran standalone. The next several articles will include code that can be ran on its own, but can also be combined with code from the other articles (and a little bit more) to produce a really nice and powerful home automation controller.

The first piece of my home automation system (HAS) that I want to share is the Python code that allows my HAS to monitor my Google Calendar. Whenever events popup on my calendar that my house needs to be aware of (such as leaving for a business trip or vacation and returning back home), my HAS will take actions accordingly. For example, whenever my fiancee and I are scheduled to leave the house for more than 24 hours, the HAS will wait until we leave and will shut off things such as the hot-water-heater, ice-machine, thermostat, etc… and will turn on other things such as the alarm (if we – or the house itself – haven’t already enabled it).

Before you can run the following code, there are a couple of things you will need to do to prepare.

1. First, you will need to create a Google account (if you haven’t already). To do that, just head over to http://www.google.com, click the blue “Sign In” button in the upper-right corner, click the “Add Account” link, and fill out the registration form. It’s best if you register for a Gmail and Google Calendar account (which I believe it does by default when you register). Once you have your Google account created, go ahead and add a couple of tasks to today’s calendar so that you’ll have something to test with later.

2. The next thing you’ll need to do is to register for a Google Developer account. You can do that by heading over to¬†https://console.developers.google.com. If you already have a Google account, you should be able to register pretty quickly for your dev account. Otherwise, create yourself a Google account as mentioned above.

3. After you have a Google Developer account, go to the Google Developer Console and click the blue “Create Project” button at the top. You can name your project whatever you want. For this example, we will call our project “My Home Automation System”.

4. With your new project created, go to the project and click on “API’s” under “API’s & Auth” on the left.

5. Scroll down to “Calendar API” and click the “OFF” button on the right. This will enable the Calendar API to be accessed from your Python code.

6. Next, click the “Credentials” link under “API’s & Auth” on the left.

7. Under “OAuth”, click the blue “Create new Client ID” button. On the popup window, select “Installed application” and “Other”, then click the “Create Client ID” button.

8. Under “Public API access”, click the “Create new Key” button, select “Server key”, and click “Create”.

You should now see something that looks like this:

Google Developer Console Credentials

CLICK TO ENLARGE

You now have everything you need to run the code below. Just make sure you copy the values from the Google Developers Console as shown above into the corresponding locations in the Python code before running it. When you do run the code for the first time, it will open your web browser to a Google page that will ask you to “Allow” your Python app to access the Calendar API using the keys you provided.

After you “Allow” your app to access your calendar the first time, the app will create a file called “calendar_creds.dat” which will store a special key that will prevent you from having to re-allow your app to access your Google account from now on. If you want to force the app to request access to your Google account again, just delete the “calendar_creds.dat” file and re-run the app.

import gflags
import httplib2
from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.tools import run
import datetime

FLAGS = gflags.FLAGS

FLOW = OAuth2WebServerFlow(
    client_id = '[CLIENT ID]',
    client_secret = '[CLIENT SECRET]',
    scope = 'https://www.googleapis.com/auth/calendar',
    user_agent = '[USER AGENT]/1.0'
    )

storage = Storage('calendar_creds.dat')
credentials = storage.get()
if credentials is None or credentials.invalid == True:
    credentials = run(FLOW, storage)

http = httplib2.Http()
http = credentials.authorize(http)

service = build(serviceName = 'calendar', version = 'v3', http = http, developerKey = '[API KEY]')

startdatetime = str(datetime.datetime.now().strftime('%Y-%m-%dT00:00:00+05:30'))
enddatetime = str(datetime.datetime.now().strftime('%Y-%m-%dT23:59:59+05:30'))

page_token = None
while True:
    events = service.events().list(calendarId = 'primary',
                                   pageToken = page_token,
                                   timeMin = startdatetime,
                                   timeMax = enddatetime).execute()

    for event in events['items']:
        print event, '\n'
    page_token = events.get('nextPageToken')
    if not page_token:
        break

Thank you for your interest in my site. If you find the information provided on this site useful, please consider making a donation to help continue development!

PayPal will open in a new tab.
$2.00
$5.00
Other

Related Posts

Leave a Reply