Saving a Year of my Life With a Smart Alarm Clock

Every morning, I wake up and spend around 20 minutes on my phone doing the following:

  • Checking the time
  • Checking the traffic from home to school
  • Checking the news
  • Checking the weather

If I continue with this routine, I will spend almost a year of my life checking the time, traffic, news and weather in the mornings.

I needed a solution that would provide me with all this information in a shorter and more efficient way. Therefore, I coded my own smart alarm clock that does those tasks for me.

Features of my Smart Alarm Clock

Below I have listed all the features my smart alarm clock contains.

Because this is an alarm clock, it has to have an alarm function. Just like any other alarm, the user inputs what time they want to wake up, and it is good to go.

Afer the alarm goes off, the smart clock announces the date and weather of a city that the user has selected.

Once the date and weather functions have been executed by the code, the user is given the option if they want to hear the news. If the user says “yes”, then the top 5 headlines are given from the following topics:

  • Politics
  • Business
  • Technology
  • Sports
  • Science

After each headline is read out, the alarm clock asks the user if they want the link to the article to be sent to them via email.

The traffic function tells the user how long it is going to take the user to get from home to their desired destination, in my case, school.

Building The Clock

For this project, I will be using Python 3.6. I will also be using the Pycharm IDE (which you can download here), though you can use any other IDE.

To get started, let’s make sure we are working in a virtual environment to make sure the packages we install don’t affect the interpreter that runs globally.

Once the virtual environment is set up, we can start to install packages.

pip install playsound
pip install pyttsx3
pip install newsapi-python
pip install SpeechRecognition
pip install secure-smtplib
pip install simplejson
pip install urllib3
pip install pyobjc

Now we can import the packages that we just installed

# Importing Packages
import datetime
from playsound import playsound
import pyttsx3
from newsapi import NewsApiClient
import speech_recognition as sr
from time import sleep
import requests
import calendar
import smtplib
import simplejson
import urllib.request

Once this is done, we can write the code to allow the user to input the time that they want to set the alarm for.

# Choosing Waking Time
alarmHour = int(input("Enter desired waking hour: "))
alarmMinute = int(input("Enter desired waking minute: "))

# Choosing am or pm
amPm = str(input("am or pm"))

# Converting to 24 hour clock
if amPm == "pm" and alarmHour != 12:
alarmHour += 12

Now we can initialize the audio engine and make the function for the clock voice.

# Initializing the audio engine
engine = pyttsx3.init()

# Audio Engine Function
def Alarm_Voice(text):
engine.say(text)
engine.runAndWait()

After that is complete, we can start to work on the news function. Before we start to write the code for this, we need to get an API key from https://newsapi.org/.

# Initializing News API Key
newsapi = NewsApiClient(api_key='INSERT API KEY HERE')

# /v2/top-headlines
politics = newsapi.get_top_headlines(q = 'politics', language='en', page_size = 1)
business = newsapi.get_top_headlines(country = 'ca', category = 'business', language='en', page_size = 1)
technology = newsapi.get_top_headlines(q = 'AI', language='en', page_size = 1)
sports = newsapi.get_top_headlines(country = 'ca', category = 'sports', language='en', page_size = 1)
science = newsapi.get_top_headlines(country = 'ca', category = 'science', language='en', page_size = 1)

# Isolating the article title
politics_article = politics['articles'][0]["title"]
business_article = business['articles'][0]["title"]
technology_article = technology['articles'][0]["title"]
sports_article = sports['articles'][0]["title"]
science_article = science['articles'][0]["title"]

# Isolating the article URL
politics_URL = politics['articles'][0]["url"]
business_URL = business['articles'][0]["url"]
technology_URL = technology['articles'][0]["url"]
sports_URL = sports['articles'][0]["url"]
science_URL = science['articles'][0]["url"]

# Article Title List
articleTitleCategory = [politics_article, business_article, technology_article, sports_article, science_article]

# Article URL List
articleURLCategory = [politics_URL, business_URL, technology_URL, sports_URL, science_URL]

# Article Dictionary
articleDictionary = {politics_article: politics_URL, business_article: business_URL, technology_article: technology_URL, sports_article: sports_URL, science_article : science_URL}

The code above basically takes the top headlines from politics, business, technology, sports and science and isolates the title and article URL.

Once we have finished the news function, we can move on to the weather. Similarly to the news function, we need to get an API key. You can get the weather API key here: https://openweathermap.org/.

Now that you have the API, we can write the code.

# Weather Function
def Weather():
appid = 'http://api.openweathermap.org/data/2.5/weather?appid=ENTER API HERE&q='
city_name = 'ENTER CITY NAME HERE'
URL = appid + city_name

json_data = requests.get(URL).json()
weather_data = json_data['weather'][0]['description']
temp_data = json_data['main']['temp']
temp_data -= 273.15
temp_data = round(temp_data)
feels_temp_data = json_data['main']['feels_like']
feels_temp_data -= 273.15
feels_temp_data = round(feels_temp_data)
return 'The weather is ' + weather_data + '. ' + 'The temperature is ' + str(temp_data) + \
' degrees Celcius and it feels like ' + str(feels_temp_data) + ' degrees Celcius in ' + city_name

Moving on to the date function, we can use the following code:

def getDate():
now = datetime.datetime.now()
my_date = datetime.datetime.today()
weekday = calendar.day_name[my_date.weekday()]
monthNum = now.month
dayNum = now.day

month_names = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']

ordinalNumbers = ['1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th', '10th', '11th', '12th', '13th', '14th', '15th', '16th', '17th', '18th', '19th', '20th', '21st', '22nd', '23rd', '24th', '25th', '26th', '27th', '28th', '29th', '30th', '31st']

return 'Today is ' + weekday + ', ' + month_names[monthNum - 1] + ' the ' + ordinalNumbers[dayNum - 1]

Great! We are almost done we just need to set up the email and traffic functions. Let's do the email first. For this function, you will have to configure your email to authenticate yourself. This can be done by creating an app password.

To do this, you will first need to enable 2-Step Verification.

Once you have enabled it, click on App passwords. Because we will be sending mail, select mail for the select app dropdown and because I am using a Mac, I will be selecting Mac as my device. Once you have selected the correct options, click generate.

You will be presented with the above screen. Make sure to copy the app password down. Once you have copied it, click done and you are now ready to write the code.

# Email Function
def send_mail(subject, body, reciever):
configPassword = 'ENTER APP PASSWORD HERE'
configEmail = 'ENTER EMAIL HERE'
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login(configEmail, configPassword)
msg = f"Subject: {subject}\n\n{body}"
server.sendmail(configEmail, reciever, msg)
server.quit()

Great! One last function. This is the traffic function. You will need to get an API key from https://developers.google.com/maps/documentation/distance-matrix/get-api-key. Make sure you set up billing for the API key, otherwise, it will not work. Once you have the key, write the following code:

def Traffic():
home_coord = "Longitude,Lattitude" # Home
work_coord = "Longitude,Lattitude" # School

# API keys (Google)
# request them here: https://developers.google.com/maps/documentation/distance-matrix/get-api-key

API1 = "ENTER API KEY HERE"

# Create the GET requests
url_home2work = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + home_coord + "&destinations=" + work_coord + "&mode=transit&traffic_model=best_guess&departure_time=now&language=en-EN&sensor=false&key=" + API1

# Preform the request and read in the JSON data
result_home2work = simplejson.load(urllib.request.urlopen(url_home2work))

# Get the driving time in seconds
driving_time_seconds_home2work = result_home2work['rows'][0]['elements'][0]['duration']['value']

return "It will take you " + str(round(driving_time_seconds_home2work/60)) + ' minutes to get from home to school'

With all the functions complete, we can finally compile the functions into a while loop to make the alarm clock.

I downloaded a .mp3 file that will play when the alarm goes off and added it to the project folder for easy access. Other than that, you have everything set up and you just need to add the following code:

# Alarm Code
while True:
if alarmHour == datetime.datetime.now().hour and alarmMinute == datetime.datetime.now().minute:
#playsound('Alarm.mp3')
#Alarm_Voice('Good morning. Hope you slept well. ' + getDate())
#Alarm_Voice(Weather())
Alarm_Voice(Traffic())
Alarm_Voice('Would you like to hear the news?')
response = recordAudio()
response.lower()
newsEmail = ""
if 'yes' in response:
for article in articleTitleCategory:
Alarm_Voice(article)
Alarm_Voice('Would you like me to send this article to you?')
response = recordAudio()
response.lower()
if 'yes' in response:
newsEmail += "\n\n" + article + ": \n" + articleDictionary[article]

send_mail('Your News Stories' , newsEmail, 'ENTER EMAIL HERE')

else:
sleep(60)
sleep(60)

Make sure you replace ENTER EMAIL HERE with the email address that will be receiving the news articles!

Conclusion

Using this alarm clock has made my mornings a lot better. I am able to be more efficient by multitasking and I am making sure I’m not using my phone first thing in the morning.

I am also able to find the top news stories in my area of interest with greater speed and because they are emailed to me, I have them saved for later.

This alarm clock uses IoT (The Internet of Things) to communicate between my laptop and email. To learn more about IoT, you can read the article that I have linked below.

With continued advances in IoT, we will be able to accomplish more in a more efficient manner. IoT is being used in many fields ranging from residential to commercial. Although this technology has a long way to go, it has the potential to revolutionize the world.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store