#!/usr/bin/python
import metoffer
import sys
import datetime
import os
import dateutil.parser
import htmlprint
from apiclient.discovery import build
from httplib2 import Http
import oauth2client
from oauth2client import client
from oauth2client import tools
import requests
import apikeys
SCOPES = 'https://www.googleapis.com/auth/calendar.readonly'
#CLIENT_SECRET_FILE = 'client_secret.json'
tomtomapi=apikeys.tomtomapi()
def get_travel_duration_tomtom(source, destination, optional=None):
if not optional:
url = "https://api.tomtom.com/routing/1/calculateRoute/{},{}:{},{}:{},{}/".format(source[0], source[1], optional[0], optional[1], destination[0], destination[1]) +\
"/json?traffic=true&key="+tomtomapi
else:
url = "https://api.tomtom.com/routing/1/calculateRoute/{},{}:{},{}:{},{}/".format(source[0], source[1], optional[0], optional[1], destination[0], destination[1]) + \
"/json?traffic=true&key="+tomtomapi
r = requests.get(url) #get the json file
trip=r.json()['routes'][0]['summary']['travelTimeInSeconds']#pull out journey time
res=(float(trip))/60
return res
def get_credentials():
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'calendar-api-quickstart.json')
store = oauth2client.file.Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatability with Python 2.6
credentials = tools.run(flow, store)
print 'Storing credentials to ' + credential_path
return credentials
def calanderprint():
"""Shows basic usage of the Google Calendar API.
Creates a Google Calendar API service object and outputs a list of the next
10 events on the user's calendar.
"""
credentials = get_credentials()
service = build('calendar', 'v3', http=credentials.authorize(Http()))
now=datetime.datetime.utcnow().isoformat() + 'Z'
#print test
#now = datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
#print now
#print 'Getting the upcoming 10 events'
eventsResult = service.events().list(
calendarId='primary', timeMin=now, maxResults=4, singleEvents=True,
orderBy='startTime').execute()
events = eventsResult.get('items', [])
if not events:
print 'No upcoming events found.'
for event in events:
# start = event['start'].get('dateTime', event['start'].get('date'))
start = event['start'].get('dateTime')#, event['start'].get('time'))
start=dateutil.parser.parse(start).strftime('%a, %H:%M')
print start, event['summary'], '<br>'
api_key=apikeys.metofficeapi()
M = metoffer.MetOffer(api_key)
weatherdata = M.nearest_loc_forecast(latitude here, longitude here, metoffer.THREE_HOURLY) #get the three hourly forcast
y = metoffer.parse_val(weatherdata) #parse the data into a useable format.
htmlprint.headhtml() #print the HTML HEAD code
x=0
for i in y.data:
if x<2:
pass #skip this as seems to the be the weather for the 2 previous hours
elif x==2:
print (str(i['Temperature'][0])+'°'+(metoffer.WEATHER_CODES[i['Weather Type'][0]])) #temperature
print ('<br></div>')
#print (metoffer.WEATHER_CODES[i['Weather Type'][0]]) #weather pic
print ('</div><div class="customfontmed">')#change to small print
print (str(i['Wind Speed'][0]))+'mph '+(str(i['Wind Direction'][0]))
print ('<br><br></div><div class="customfontsmall">')
elif x==21: #only show 9 forcasts
break
#else:
#print('{}- {}'.format(i['timestamp'][0].strftime('%a, %H:%M '))
elif x % 2 ==0:
print('{}           {}'.format(i['timestamp'][0].strftime('%a, %H:%M '), metoffer.WEATHER_CODES[i['Weather Type'][0]])+str(i['Temperature'][0])+'°'+"")+" "+(str(i['Wind Speed'][0]))+'mph '+(str(i['Wind Direction'][0])+'<br>')
else:
pass
#print (str(i['Temperature'][0])+'°'+"<br>")
##print('<br>')
x=x+1
#print('</td><td style="border-width : 0px;"><iframe src="http://free.timeanddate.com/clock/i46u0mcs/n1233/fn17/fs48/fcfff/tc000/pc000/ts1" frameborder="0" width="238" height="61"></iframe>')
print ('</div><div class="customfontsmallsmall"> <font color="white"><br>')
busarrary=[datetime.time(7,33), datetime.time(9,35),datetime.time(10,30),datetime.time(11,35),datetime.time(12,30),datetime.time(13,35),datetime.time(14,30),datetime.time(15,30),datetime.time(16,30),datetime.time(17,29)] #bus times
hr=datetime.datetime.now().time()
x=0
wday=datetime.datetime.today().weekday()
#wday=6
#x=10
home_lat=latitude here,
home_long= longitude here
home = (home_lat, home_long)
work = (latitude here, longitude here )
route1 =latitude here, longitude here
route2=latitude here, longitude here
if sys.argv[1]=="2": #only do traffic stuff if called i.e. only in the morning.
if __name__ == '__main__':
print "<br><br>"
res = get_travel_duration_tomtom(home, work, route1)
print "Time to work via Route One "+str( res)+ " minutes<br>"
res = get_travel_duration_tomtom(home, work, route2)
print "Time to work via Route two "+str( res)+ " minutes<br>"
#***********************************************************************#
#bus portion
while True:
if x==10 or wday==6:
print "Next Bus at " + format(busarrary[0].strftime('%H:%M'))
break
elif busarrary[x] > hr:
print "Next Bus at " + format(busarrary[x].strftime('%H:%M'))
break
x+=1
if wday==5 and x==10:
print "Monday"
elif wday==6 or x==10:
print "Tomorrow"
else:
print "Today"
if wday==2:
print "Bins"
if sys.argv[1]=="1": #if called get the calander details
if __name__ == '__main__':
print "<br><br>"
# calanderprint()
htmlprint.htmlend()
No comments:
Post a Comment