This post isn’t really thumbnail conducive but I tried!
I have been sleeping in too much. I would like an alarm clock that is easy to set and will play a random song to wake me up.
For a while I was using this program, but as you may be able to tell it requires an awful lot of user input, which isn’t ideal for a sleepy person as they may mess up (as I have, thus this post) but the “fire()” command works really well. To use this program you will need AP scheduler and MPG321 (sudo apt-get install mpg321)
But it wasn’t working. I wanted a way to re-purpose a service I use everyday (that way I wouldn’t have to modify my workflow) as an Alarm Clock. I landed on Google Calendar because I can add events from pretty much every device I interact with on a daily basis, and upon searching found out that developing using the python API wasn’t that hard at all.
To kick things off, you’ll need to download and install the Google Data Library.
I’ll be using this version. Unzip the .tar.gz and from the top top level directory it creates, install the setup.py file. Then run the tests/run_data_tests.py to see if it all works. Mine does fine but it if yours doesn’t, go through this guide written by google to get yourself up and running.
The brunt of this program comes down to a single boolean statement, but first we have to set that up. The API produces an rfc3339 time, and that’s a lot of irrelevant information for this application.
To convert the time I’m using something I found on stackoverflow.
Here’s a video of the system in action, and a basic overview of the setup:
Here’s my program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
#These are the imports google said to include import gdata.calendar.service import gdata.service import atom.service import gdata.calendar import gdata.calendar import atom import getopt import sys import string import time import xe #for the time comparator from feed.date.rfc3339 import tf_from_timestamp #also for the comparator from datetime import datetime #for the time on the rpi end from apscheduler.scheduler import Scheduler #this will let us check the calender on a regular interval import os, random #to play the mp3 later #this is more stuff google told me to do, but essentially it handles the login credentials calendar_service = gdata.calendar.service.CalendarService() calendar_service.email = 'youremail@yourdomain' #your email calendar_service.password = 'yourgcalpassword' #your password calendar_service.source = 'Google-Calendar_Python_Sample-1.0' calendar_service.ProgrammaticLogin() def FullTextQuery(calendar_service, text_query='wake'): print 'Full text query for events on Primary Calendar: \'%s\'' % ( text_query,) query = gdata.calendar.service.CalendarEventQuery('default', 'private', 'full', text_query) feed = calendar_service.CalendarQuery(query) for i, an_event in enumerate(feed.entry): for a_when in an_event.when: print "---" print an_event.title.text ,"Number:",i,"Event Time:",time.strftime('%d-%m-%Y %H:%M',time.localtime(tf_from_timestamp(a_when.start_time))),"Current Time:",time.strftime('%d-%m-%Y %H:%M') if time.strftime('%d-%m-%Y %H:%M',time.localtime(tf_from_timestamp(a_when.start_time))) == time.strftime('%d-%m-%Y %H:%M'): print "Comparison: Pass" print "---" songfile = random.choice(os.listdir("/home/pi/alarmclock/test_MP3s/")) #chooses the .mp3 file print "File Selected:", songfile command ="mpg321" + " " + "/home/pi/alarmclock/test_MP3s/" + "'"+songfile+"'"+ " -g 100" #plays the MP3 in it's entierty. As long as the song is longer than a minute then will only trigger once in the minute that start of the "wake" event print command os.system(command) #runs the bash command else: print "Comparison:Fail" #the "wake" event's start time != the system's current time def callable_func(): os.system("clear") #this is more for my benefit and is in no way necesarry print "------------start-----------" FullTextQuery(calendar_service) print "-------------end------------" scheduler = Scheduler(standalone=True) scheduler.add_interval_job(callable_func,seconds=5) scheduler.start() #runs the program indefinatly on an interval of 5 seconds |
And there you have it! thanks for reading and leave me a comment if you have any questions/suggestions.
Hi, i’m really a noob, but i want to try this 😀
..but where i have to paste you code? i have to create a .py file? where i have to put this file?
Hi! You do have to create a file, and the code is the green block of the blog post. I suggest downloading and installing a program called geany for the raspberry pi
Ok, i’ve created correctly the file, but it gives me an error at line 14, it doesn’t find xe module. It’s a google module?
Did you install PYFeed?
Hey
This is awesome
What OS do you run on your pi
Hi
YOU’RE AWESOME
the latest raspian build
Thanks for the tip! Very helpfull
Thanks for the great comment!
Re: Error at line 14 – no ‘xe’
I had the same problem.
You have to install a python module ‘pyfeed’ which gives you the xe and some other items used in the program. I found it at
http://home.blarg.net/~steveha/pyfeed.html
yeah I guess I didn’t make that clear enough, thanks for pointing it out!
Fantastic! Tnx for help 😉
I think there is a little bug.
If i set the wake event on calendar with the option ‘repeat every day’ it doesn’t work…
It’s a common problem?
hmm! I haven’t used this feature in google cal as I don’t really have a regimented wake up schedule. Please comment again if you come up with a solution!
Hi,
this is a nice idea, I have been playing with the Google Calendar API on my Pi for a different project. I have created a Meeting Room display.
The singleEvents=True parameter splits repeating events into single events.
https://developers.google.com/google-apps/calendar/v3/reference/events/list
HTH
Bruce
After using singleevents,still can not been prefect fixed .
According to analyze the source code, the following can fixed:
47 query.orderby = ‘starttime’
48 query.singleevents = ‘true’
49 query.sortorder = ‘a’
50 query.futureevents = ‘true’
More info, pls refter to src/gdata/calendar/service.py
Sorry, my englist is poor
So does this fix work? Should I update my post?
Hi Devon or Cia91
Did you find out how to fix problem with repeat every day.
It’s almost perfect working with my lights turn of on.
thanks,
No I haven’t really had the need to use that feature as I wake up at a different time almost daily. If you figure it out please feel free to post here!
See my reply that i posted a few months ago. It tells you how you can add it in. It also tells you about another bug.
Eddie Bijnen Idon’t now how to change it to youre way.
I add After line 28 fallowing:
query.singleevents = ‘true’
query.orderBy = ‘startTime’
query.sortorder = ‘ascending’
but i get back a error
Try the solution posted from Bruce
I just got a Pi, and happened across a Zen Alarm clock (130 bucks new, 4 bucks for me). I plan on wiring the striker into a GPIO channel, and use a 2 line LED display instead of the clock face. The only piece I needed, you’ve written.
Thank you!
Please leave a link for any work related to your project as I’m very interested!
I cannot thank you enough for making this little gem.
Not only have I got something that integrates perfectly with my workflow to wake me up in an easy and effective manner, I have learnt more about my pi and python from following this code.
My deepest thanks!
Warmest regards,
Stephen
Thank you for this very nice comment!
Hey there, I wanted to try this out but i kept running into problems ( iv never had to use python before).
Iv installed python, pyfeed and even the xe just incase but I am getting an error for line 16 import error no module named apscheduler.scheduler.
please help?
Thanks for giving this a go!
You will need to install AP scheduler https://pypi.python.org/pypi/APScheduler/
Now its saying 2-13 import not found, cant read /var/mail/feed.date.rfc3339, /var/mail/datetime, /var/mail/apscheduler.scheduler. 17-19 import not found, 20 syntax error ( unexpected.
really not liking python so far haha.
Thank you very much for your help so far though!
hi! can you post your code to pastebin?
pi@raspberrypi ~ $ cd /share
pi@raspberrypi /share $ sudo ./pi-alarm.py
./pi-alarm.py: 2: ./pi-alarm.py: import: not found
./pi-alarm.py: 3: ./pi-alarm.py: import: not found
./pi-alarm.py: 4: ./pi-alarm.py: import: not found
./pi-alarm.py: 5: ./pi-alarm.py: import: not found
./pi-alarm.py: 6: ./pi-alarm.py: import: not found
./pi-alarm.py: 7: ./pi-alarm.py: import: not found
./pi-alarm.py: 8: ./pi-alarm.py: import: not found
./pi-alarm.py: 9: ./pi-alarm.py: import: not found
./pi-alarm.py: 10: ./pi-alarm.py: import: not found
./pi-alarm.py: 11: ./pi-alarm.py: import: not found
: not foundpy: 12: ./pi-alarm.py:
./pi-alarm.py: 13: ./pi-alarm.py: import: not found
from: can’t read /var/mail/feed.date.rfc3339
from: can’t read /var/mail/datetime
from: can’t read /var/mail/apscheduler.scheduler
./pi-alarm.py: 17: ./pi-alarm.py: import: not found
: not foundpy: 18: ./pi-alarm.py:
./pi-alarm.py: 20: ./pi-alarm.py: Syntax error: “(” unexpected
pi@raspberrypi /share $
Is there a setup I failed to run?
Is there something i failed to install?
I get the same errors stated by Josh. I’ve tried updating gData and raspbian but on line 2 the import: not found.
How do I run the program?
download and install python, download and install the libraries listed above, and run the code!
Hello, your idea is amazing and just tha I need. But I have an error: ImportError: cannot import name tf_from_timestamp.
Really, I don’t know what happen.
Maybe the problem could be my OS, Raspbmc.
Thank you very much!
did you install this library? http://home.blarg.net/~steveha/pyfeed.html
Yes, pyfeed, xe and google data.
Thanks for answer.
I am having the same problem. I’ve installed all of the listed libraries and still get “cannot import name tf_from_timestamp” Were you able to solve this somehow?
Works very well!! Thanks for publishing!
Is there anyone who knows how to alter the code for the SingeEvent=TRUE parameter. I tried interting it in several ways, but my understanding of this way of programming is not enough to get it working. Normally Google is my best friend, but after searching for several hours, i found no solution. TYVM!
Hmm, this isn’t really relevant to my application, but if you figure out what’s going on, please report back!
This code uses v2 of the Google Calendar API, I have done some work with v3 and used SingleEvents=True . v3 is a bit different, especially with authentication, but not that hard to use once you work out which code to steal from google’s dev site. Details on my blog.
I’ve had a play with the Google Calendar API v3 and the idea of getting the time from an event named “wake”, even when it is repeating.
The code is here if anyone wants it as a basis, you just need to get a Google API key
https://code.google.com/apis/console
http://pastebin.com/u5ht1YAe
HI BruceR,
i have made the follow code to control my lights,
http://pastebin.com/KDwhzjNG
i hope you can help me to change it to youre script
when i run youre script i get the follow;
error:
File “herhaalcalendar.py”, line 3
import gflags
thanks,
klaas
Uehhh Klaas I think it’s time you change you’re MySQL password. And pray to god you didn’t just post you’re default password for everything 😛
Have you installed the API library?
You will need the python-setuptools package:
sudo apt-get install python-setuptools
Then I installed the api package ..
sudo easy_install –upgrade google-api-python-client
Works perfect! Thank you for some awesome code. I mirrored on my site giving credit and some detailed steps for the extra parts I had to install.
Hi . Thank you for your post. I am getting the following error:
Output:
File “Alarm.py”, line 41
os.system(command)
^
IndentationError: unexpected indent
Code:
command =”mpg321″ + ” ” + “/home/pi/Alarm/” + “‘”+songfile+”‘”+ ” -g 100″
Thank you
Hi! It would appear that you copy-pasted incorrectly. Try doing it again.
is it possible that mpg321 is not installed on your system? I remember the error and I think installing mpg321 resolved it.
check also that the /home/pi/Alarm/-folder is present and that upper/lowercase matches the command. It also has to have mp3s in it which can be played.
Hi,
So I have put the Google Data Library on my Pi and have unzipped it. I have also put on the xe module. When I go into python I copy the code from the website and fill in my email and password. I have also put a mp3 into the designated folder, But as soon as I try to run the program I get syntax errors over and over. Is there something that I am doing wrong or not installing
please comment the errors you are having!
There’s an error in your program:Invalid syntax. Every error I would get I would delete and run the program again. I got this at ln:12 ln:18 ln:27 and more.
Thanks,
Cameron
Working on getting the script to accept recurring events but i just got to say.
GOOGLE YOU’RE *$@#$^ Reference material sucks. Twice it has just been flat out WRONG
RECURRING EVENTS FIX:
Am not a programmer and I get frustrated really fast. But I did manage to get something done.
After line 28 add the fallowing
query.singleevents = ‘true’
query.orderBy = ‘startTime’
query.sortorder = ‘ascending’
But there is a bug in the original program that screws up this fix. Only the first 24 results will be posted. So if you have more the 24 wake’s in your calender then it won’t launch your mp3!!! With this fix and without.
This can be fixed by adding an combo of the fallowing commands.
time.strftime(‘%Y-%m-%d %H:%M’)
query.timemin = ‘2013-07-05T10:57:00-08:00’
But I got to frustrated at this point.
it’s even better to add
query.max_results = ‘5’
to limit number of recurring events. it helps with the “bug”
This works great! Thanks for the help man!
No probs! A little bit of annoyance and googling afterwards and viola! http://gdata-python-client.googlecode.com/hg/pydocs/I Btw, I’m working with your code, hope you don’t mind, to create a controllable alarm service. Posted about it on my blog. Thanks!
It cut off the link… http://gdata-python-client.googlecode.com/hg/pydocs/gdata.calendar.service.html
Hey, thanks for an awesome post!
I’ve got it working, and everything seems to work, but I get the error:
No handlers could be found for logger “apscheduler.scheduler”
Any ideas???
Hey, thanks for the comment try adding “import logging logging.basicConfig()” to your code and tell me how it goes!
Hi, i’ve the same error and when i write your solution have this:
import logging logging.basicConfig()
SyntaxError: invalid syntax
An idea ? Thx
Now i have this: http://hpics.li/bc607e7
the mess come every 5 sec that why i made a Screenshots : )
I got this error too. Did you find a solution for that?
I’ve managed to make it response to recurring events. on line 28 add ‘singleevents=true’ in the query body: query = gdata.calendar.service.CalendarEventQuery(‘default’, ‘private’, ‘full’, text_query, ‘singleevents=true’) and it works well.
hello,
I am trying to download the XE library and have a few problems. It takes me to https://myaccount.avvanta.com/ where it asks me for a registration number and password and I don’t see any way of getting that. How did you get the XE libraries?
Thanks,
Blake
Try this wget http://sourceforge.net/projects/salix-sbo/files/13.37/xe/xe-0.7.4.tar.gz
Hello guys,
Is it possible to have the code file wake.py because I have a error but I don’t find it. thanks in advance
Just want to say, nice work!
Looking forward to some more similar stuff!
Very nice, thanks for posting this! Was testing this out and noticed a few things have changed since you’ve written it (like the way apscheduler works– doesn’t seem to have .scheduler available now) so I updated it and cleaned it up a bit. Using mpg123 instead of mpg321 and no real need to use xe or the feed/atom stuff. Running this locally on a Mac, you can install gdata and apscheduler with pip; I only had to install mpg123 locally from here: http://www.mpg123.de/download.shtml
Here’s the python code:
http://pastebin.com/CSyp6fMi
To update my previous comment, I’ve re-written it to use Google’s v3 API / OAuth and to play mp3s based on event names:
https://github.com/ehamiter/get-on-the-bus
Thanks for the inspiration!
Thanks for all of your work!
Very good
I was using old API and was stoppes from Nov 17
I will study it to understand behavior
Could you tell me more about PIP?
I have tried your script but it’s not working
I get a message to inform “gflags” will be soom unavailabe, and nothing more. Script is not closed but nothing happend
An idea?
Hi,
Your code works for me, next to that i have an another script for control the relay with the GPIO 11, i would like blend the two script, so i writed that(just with the important parts where i changed somthing)
import atom
import getopt
import sys
import string
import time
import RPi.GPIO as GPIO
[…]
calendar_service.source = ‘Google-Calendar_Python_Sample-1.0’
calendar_service.ProgrammaticLogin()
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(11,GPIO.OUT)
[…]
songfile = random.choice(os.listdir(“/home/pi/alarmclock/test_M$
print “File Selected:”, songfile
command =”mpg321″ + ” ” + “/home/pi/alarmclock/test_MP3s/” + “‘$
GPIO.output(11,GPIO.HIGH)
print command
os.system(command) #runs the bash command
else:
$ the system’s current time
The problem is there is error with GPIO.setwarnings(False) and i don’t realy know how to resolve this problem :S do you have an idea ?
Thx !
I have a new version of RPi.GPIO and the error disapear, i put the GPIO.output(11,GPIO.HIGH) before songfile = random.choice
So now the light is activated in the same time : D, i stop the light simply with an android app wich control the GPIO.
I have anothers ideas now so i will maybe comeback !
I am getting “ImportError: No module named scheduler”
I have APScheduler installed and everything else seems fine
Anyone have any ideas
you can do following
sudo pip install –upgrade pip
sudo pip uninstall apscheduler
sudo pip install apscheduler==2.1.2
but so sorry that the query script is not working on latest google calendar api
its sudo pip install –upgrade pip (two dashes)
Same here! Help?
Hi! These comments are pretty informative, try (sudo pip install –upgrade pip)
can u teach me step by step..im noob
Hi Devon!
I have some problem.
when I finished installing apscheduler.scheduler, it showed me that”
error: Setup script exited with error in funcsigs setup command: Invalid environment marker: python_version<"2.7"
"
Could you tell me what happened?
How can I fix this bug?
Hi Devon!
I have some problem.
when I finished installing apscheduler.scheduler, it showed me that”
error: Setup script exited with error in funcsigs setup command: Invalid environment marker: python_version<"2.7"
"
Could you tell me what happened?
How can I fix this bug?
Hi Devon
OK, I solved this problem. But now I have a new problem.
print ‘Full text query for events on Primary Calendar: \’%s\” % ( text_query,)
SyntaxError: invalid syntax-bash: SyntaxError:: command not found
What happened?
How did you solve the problem
Hah, I’m really a noob. Now I know, a command called python3.Haha
do you have an example of this program”wake calender” (it does not work on mine)
My code isn’t going inside the feed.
I tried printing comments above and below this to see til where the code works, it just wont go after this command
feed = calendar_service.CalendarQuery(query)
Can you please help me out.