def sunriseAlarm(): """ Description: Pre-sunrise alarm giving users a chance to get up in time to see sunrise """ logger.info("Time for pre-sunrise alarm") speak.speakGreeting() speak.speakString("in case you are awake,") quips = [ "consider going out to watch sunrise", "sun will rise soon. I thought you might be interested to know"] tempint = randint(1,len(quips)) greeting = quips[tempint-1] speak.speakGreeting(greeting)
def smartAlarm(): """ Description: morning alarm function. ### TO DO - rework this whole utility as a generic smart alarm ### purpose specific alarms are written separately """ logger.info("Time to ring alarm") speak.speakGreeting() if (datetime.datetime.now().hour > 5) and (datetime.datetime.now().hour <= 12): logger.info("Good Morning!") speak.speakString("your time to rest has come to an end") speak.speakTime() speak.speakDate() try: loc = location.getLocation("freegeoip") weatherUtil.getWeather(loc[1],loc[2]) except Exception, e: logger.error("Failed to get weather info") logger.error("Traceback: "+str(e)) # gmail logger.info("Gmail check") unread_count = speak.getUnreadCount() # not sure why i did this if unread_count > 1: speak.speakString("While you were sleeping "+str(unread_count)+" emails flooded your inbox") # check calendar logger.info("Calendar check") events = googleUtil.calendarToday() if events: if len(events) == 1: logger.info("you have only one event today") event_title = events[0]['summary'] try: event_time = datetime.datetime.strptime(events[0]['start'].get('dateTime').split("T")[1][:-6][:5], '%H:%M') speak.speakString("Today you have " + event_title + " at " + str(event_time.hour)) except: # this happens for full day events speak.speakString("Today you have " + event_title) else: logger.info("you have several events today") speak.speakString("Don't make many plans. You have several events scheduled for today") for i in range(len(events)): if i == 0: speak.speakString("Your first event of the day is ") if i == len(events)-1: speak.speakString("and your last event of the day is ") else: speak.speakString("then you have ") event_title = events[i]['summary'] try: event_time = datetime.datetime.strptime(events[i]['start'].get('dateTime').split("T")[1][:-6][:5], '%H:%M') speak.speakString(event_title + " at " + str(event_time.hour)) except: # this happens for full day events speak.speakString(event_title) try: # audio.playMorningMedia() logger.info("morning aduio playback is disabled for the moment") except Exception, e: logger.error("Failed to play alarm music") logger.error("Traceback: "+str(e))
owner.getDetails("armageddion") ishome = owner.state if (ishome == 'online'): logger.info("Bed time, maybe?") quips = [ "Unless we are burning the midnight oil, ", "If you are going to invent something new tomorrow, ", "If you intend on being charming tomorrow, "] tempint = randint(1,len(quips)) greeting = quips[tempint-1] greeting += "perhaps you should consider getting some rest." speak.speakString(greeting) event_tomorrow = googleUtil.calendarTomorrow() event_tomorrow_title = event_tomorrow['summary'] event_tomottow_time = datetime.datetime.strptime( event_tomorrow['start'].get('dateTime').split("T")[1][:-6][:5], '%H:%M') speak.speakString("Your first event tomorrow is "+event_tomorrow_title+" at "+str(event_tomottow_time.hour)) return def sunriseAlarm(): """ Description: Pre-sunrise alarm giving users a chance to get up in time to see sunrise """ logger.info("Time for pre-sunrise alarm")
# just gotta clean it up because sometimes we get garbage in the city name city_new = re.sub('[^A-Za-z]+', "", city_new) logger.info("IP:" + str(ip_new)) logger.info("City:" + str(city_new)) logger.info("Sate/Prov:" + str(state_new)) logger.info("Country:" + str(country_new)) logger.info("Longitude: " + str(long_new)) logger.info("Latitude: " + str(lat_new)) if city_new == city: #print "still in the same place" logger.info("You are still in the same location") else: logger.info("Oh hello! Welcome to " + city_new) speakString("Welcome to " + city_new + " sir") speakString("I trust you enjoyed your travels") # get latest weather info for new location getWeather(city_new, country_new) try: logger.info("Updating environment databse") collection_env.update({"name": socket.gethostname()}, { "$set": { "country": country_new, "state": state_new, "city": city_new, "IP": ip_new, "latitude": lat_new, "longitude": long_new
city_new = info6['city'] ip_new = info6['address'] else: raise Exception("Unable to get geo info based on IP") except Exception, e: log.write(strftime("%H:%M:%S: ")+"Error getting my location:"+e+"\n") sys.exit(1) if city_new == city: print "still in the same place" log.write(strftime("%H:%M:%S: ")+"You are still in the same location\n") else: log.write(strftime("%H:%M:%S: ")+"Oh hello! Welcome to "+city_new+"\n") speak.speakString("Welcome to "+city_new+" sir") speak.speakString("I trust you enjoyed your travels") # get latest weather info for new location weatherUtil2.getWeather2(city_new, country_new) collection_env.update({"name":socket.gethostname()},{"$set":{ "country":country_new, "state":state_new, "city":city_new, "IP":ip_new}}) log.close() # Main - only really used for testing if __name__ == '__main__':
def getWeather2(city="Toronto",country="CA"): """ Description: This function gets weather data and parses it. Return: Boolean; True if successful, False if not. """ logfile = os.path.join(os.path.join(os.getcwd(),os.path.dirname(__file__)),"../log/weatherUtil2.log") f = open(logfile, 'a') # get API key for db-ip.com config = ConfigParser.RawConfigParser() config.read(os.path.join(os.path.dirname(__file__),'../config/apikeys.conf')) apikey = config.get("API KEY", "openWeather") weatherData = None #url = "http://api.openweathermap.org/data/2.5/weather?q="+city+","+country url = "http://api.openweathermap.org/data/2.5/weather?q="+city+","+country+'&appid='+apikey try: weatherData = json.loads(urllib.urlopen(url).read().decode('utf-8')) except: f.write(strftime("%H:%M:%S: ")+"Failed to get weather data\n") return False, weatherData f.write(strftime("%H:%M:%S: ")+"got weather data\n") #log current conditions f.write(strftime("%H:%M:%S: ")+"City: "+str(weatherData['name'])+"\n") f.write(strftime("%H:%M:%S: ")+"Wind Speed: "+str(weatherData['wind']['speed'])+"\n") f.write(strftime("%H:%M:%S: ")+"Atmospheric Pressure "+str(weatherData['main']['pressure'])+"\n") f.write(strftime("%H:%M:%S: ")+"Humidity "+str(weatherData['main']['humidity'])+"\n") f.write(strftime("%H:%M:%S: ")+"Today's Low: "+str(KtoC(weatherData['main']['temp_min']))+"\n") f.write(strftime("%H:%M:%S: ")+"Today's High: "+str(KtoC(weatherData['main']['temp_max']))+"\n") f.write(strftime("%H:%M:%S: ")+"Description: "+str(weatherData['weather'][0]['description'])+"\n") f.write(strftime("%H:%M:%S: ")+"Current Temperature: "+str(weatherData['main']['temp'])+"\n") f.write(strftime("%H:%M:%S: ")+"Parsed weather data\n") # Subjective weather badDay = [] badDay_data = [] badDay.append(False) badDay.append(badDay_data) # if weather is bad... if weatherData['weather'][0]['main'] in ['Thunderstorm','Drizzle','Rain','Snow','Atmosphere','Exreeme']: badDay[0] = True badDay[1].append(weatherData['weather'][0]['description']) elif weatherData['main']['humidity'] > 50: badDay[0] = True badDay[1].append(weatherData['main']['humidity']) if KtoC(weatherData['main']['temp_max']) > 27: badDay[0] = True badDay[1].append(weatherData['main']['temp_max']) elif KtoC(weatherData['main']['temp_min']) < -5: badDay[0] = True badDay[1].append(weatherData['main']['temp_min']) if weatherData['wind']['speed'] > 10: badDay[0] = True badDay[1].append(weatherData['wind']['speed']) f.write(strftime("%H:%M:%S: ")+"Speaking weather data:\n") # Speak the weather data greeting = '' random = ["Weather patterns ", "My scans "] greeting += random[randint(0,len(random)-1)] global hour if badDay[0]: speakString("I am afraid I don't have good news sir.") greeting+="indicate " for i in range(len(badDay[1])): if badDay[1][i] == weatherData['weather'][0]['main']: greeting += badDay[1][i] elif badDay[1][i] == weatherData['main']['humidity']: greeting += "humidity of a steam bath" elif badDay[1][i] == weatherData['main']['temp_max']: greeting += "it is too hot for my gentle circuits" elif badDay[1][i] == weatherData['main']['temp_min']: greeting += "it is catalysmically cold" elif badDay[1][i] == weatherData['wind']['speed']: greeting += "the wind will seriously ruin your hair" if len(badDay[1])>=2 and i < (len(badDay[1])-1): add = [' also ',' and if that isn\'t enough ', ' and to make matters worse '] greeting += add[randint(0,len(add)-1)] elif len(badDay[1])>2 and i == (len(badDay[1])-1): greeting += " and on top of everything " else: f.write(strftime("%H:%M:%S: ")+greeting+"\n") speakString(greeting) else: speakString("Weather today is just gorgeous!") greeting += "indicate "+weatherData['weather'][0]['description'] speakString(greeting) f.write(strftime("%H:%M:%S: ")+greeting+"\n") speakString("Current temperature in "+weatherData['name']+" is "+str(KtoC(weatherData['main']['temp']))+" degrees") if (ampm=="AM" and int(hour)<10): speakString("Today\'s high is expected to be "+str(KtoC(weatherData['main']['temp_max']))+" degrees") f.write(strftime("%H:%M:%S: ")+"Spoke weather\n") return True f.close()
def getWeather(city="Toronto", country="CA"): """ Description: This function gets weather data and parses it. Return: Boolean; True if successful, False if not. """ # get API key for openWeather logger.info("Getting weather data for " + city + ", " + country) config = ConfigParser.RawConfigParser() config.read(os.path.join(os.path.dirname(__file__), '../conf/apikeys.conf')) apikey = config.get("API KEY", "openWeather") db_user = config.get("Alfr3d DB", "user") db_pass = config.get("Alfr3d DB", "password") weatherData = None url = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "," + country + '&appid=' + apikey try: weatherData = json.loads(urllib.urlopen(url).read().decode('utf-8')) except: logger.error("Failed to get weather data\n") return False, weatherData logger.info("got weather data for " + city + ", " + country) logger.info(weatherData) # DEBUG #log current conditions logger.info("City: " + str(weatherData['name'])) logger.info("Wind Speed: " + str(weatherData['wind']['speed'])) logger.info("Atmospheric Pressure " + str(weatherData['main']['pressure'])) logger.info("Humidity " + str(weatherData['main']['humidity'])) logger.info("Today's Low: " + str(KtoC(weatherData['main']['temp_min']))) logger.info("Today's High: " + str(KtoC(weatherData['main']['temp_max']))) logger.info("Description: " + str(weatherData['weather'][0]['description'])) logger.info("Current Temperature: " + str(KtoC(weatherData['main']['temp']))) logger.info( "Sunrise: " + str(strftime('%H:%M', localtime(weatherData['sys']['sunrise'])))) logger.info( "Sunset: " + str(strftime('%H:%M', localtime(weatherData['sys']['sunset'])))) logger.info("Parsed weather data\n") # Initialize the database client = MongoClient( 'mongodb://ec2-52-89-213-104.us-west-2.compute.amazonaws.com:27017/') client.Alfr3d_DB.authenticate(db_user, db_pass) db = client['Alfr3d_DB'] collection_env = db['environment'] logger.info("Updating weather data in DB") collection_env.update({"name": socket.gethostname()}, { "$set": { "weather": { "sunrise": str(weatherData['sys']['sunrise']), "sunset": str(weatherData['sys']['sunset']), "todays_high": str(KtoC(weatherData['main']['temp_max'])), "todays_low": str(KtoC(weatherData['main']['temp_min'])) } } }) # Subjective weather badDay = [] badDay_data = [] badDay.append(False) badDay.append(badDay_data) # if weather is bad... if weatherData['weather'][0]['main'] in [ 'Thunderstorm', 'Drizzle', 'Rain', 'Snow', 'Atmosphere', 'Exreeme' ]: badDay[0] = True badDay[1].append(weatherData['weather'][0]['description']) elif weatherData['main']['humidity'] > 65: badDay[0] = True badDay[1].append(weatherData['main']['humidity']) if KtoC(weatherData['main']['temp_max']) > 27: badDay[0] = True badDay[1].append(weatherData['main']['temp_max']) elif KtoC(weatherData['main']['temp_min']) < -5: badDay[0] = True badDay[1].append(weatherData['main']['temp_min']) if weatherData['wind']['speed'] > 10: badDay[0] = True badDay[1].append(weatherData['wind']['speed']) logger.info("Speaking weather data:\n") # Speak the weather data greeting = '' random = ["Weather patterns ", "My scans "] greeting += random[randint(0, len(random) - 1)] # Time variables hour = strftime("%I", localtime()) minute = strftime("%M", localtime()) ampm = strftime("%p", localtime()) if badDay[0]: speakString("I am afraid I don't have good news.") greeting += "indicate " for i in range(len(badDay[1])): if badDay[1][i] == weatherData['weather'][0]['description']: greeting += badDay[1][i] elif badDay[1][i] == weatherData['main']['humidity']: greeting += "humidity of a steam bath" elif badDay[1][i] == weatherData['main']['temp_max']: greeting += "it is too hot for my gentle circuits" elif badDay[1][i] == weatherData['main']['temp_min']: greeting += "it is catalysmically cold" elif badDay[1][i] == weatherData['wind']['speed']: greeting += "the wind will seriously ruin your hair" if len(badDay[1]) >= 2 and i < (len(badDay[1]) - 1): add = [ ' , also, ', ' , and if that isn\'t enough, ', ' , and to make matters worse, ' ] greeting += add[randint(0, len(add) - 1)] elif len(badDay[1]) > 2 and i == (len(badDay[1]) - 1): greeting += " , and on top of everything, " else: logger.info(greeting + "\n") speakString(greeting) else: speakString("Weather today is just gorgeous!") greeting += "indicate " + weatherData['weather'][0]['description'] speakString(greeting) logger.info(greeting + "\n") speakString("Current temperature in " + weatherData['name'] + " is " + str(KtoC(weatherData['main']['temp'])) + " degrees") if (ampm == "AM" and int(hour) < 10): speakString("Today\'s high is expected to be " + str(KtoC(weatherData['main']['temp_max'])) + " degrees") logger.info("Spoke weather\n") return True f.close()