示例#1
18
def weatherCheck(inputText): # extract all relavent information from input text, returns a dictionary result
    print "Checking weather!"
    output = {}
    owm = OWM()
    longitude = 0
    latitude = 0

    if (owm.is_API_online()):
        print "OWM API is ONLINE"
        try: #Try to find location of device
            country = ""
            city = ""
            for c in ["canada", "us", "united states"]:
                if (str.find(inputText, c) != -1):
                    country = c

            cityList = []
            fil = open("city_list.txt", "r")
            for line in fil:
                cityData = line.split("\t")
                cityList.append([cityData[1], cityData[4]]) #City name and country
            fil.close()
            
            for c in cityList:
                if (c[0] != "" and common.wholeWordFind(inputText, c[0])):
                    city = c[0]
                    if (country == ""): #If we didn't find a country yet, specify it from the city
                        country = c[1].strip()
                    break
            
            if (country == "" or city == ""):
                raise NameError("No location")
            
        except NameError:
            if ((country == "") ^ (city == "")): #Logical xor
                print "Couldn't find the city and/or country: (city="+city+", country="+country+")"
            location = common.getLocation()
            city = location["city"]
            country = location["country_name"]

        print "City is "+city
        print "Country is "+country
        obs = owm.weather_at_place(city+","+country)
        
        w = obs.get_weather()
        output["clouds"] = w.get_clouds() #Cloud coverage
        output["rain"] = w.get_rain() #Rain volume
        output["snow"] = w.get_snow() #Snow volume
        output["wind"] = w.get_wind() #Wind direction and speed
        output["humidity"] = w.get_humidity() #Humidity percentage
        output["pressure"] = w.get_pressure() #Atmospheric pressure
        output["temperature"] = w.get_temperature("celsius") #Temperature
        output["status"] = w.get_detailed_status() #Get general status of weather
        output["sunrise"] = w.get_sunrise_time() #Sunrise time (GMT UNIXtime or ISO 8601)
        output["sunset"] = w.get_sunset_time() #Sunset time (GMT UNIXtime or ISO 8601)
    else:
        print "OWM API is OFFNLINE, FAILED"
        output["status"] = "FAILED"
    return output
示例#2
5
文件: weather.py 项目: Xav-Deb/jarvis
def main():
	API_key = 'e1c56e2dfcb9660ac9cfdbf1dc0ccd99'
	owm = OWM(API_key, version='2.5', language='fr')
	obs = owm.weather_at_place('Lille,fr')
	w = obs.get_weather()
	#meteo = u'Il est %s heure %s.\n' % (time.strftime("%H"),time.strftime("%M"))
	meteo = u'Sur Lille, le temps est %s et la température est de %s degré.\n' % (w.get_detailed_status(), w.get_temperature(unit='celsius')['temp'])
	return(meteo)
示例#3
1
 def initialize(self):
     self.log=LoggerFactory.get_file_logger(config.log_filename,"WeatherRealtimeUpdaterThread",config.log_level)
     self.log.info("Initializing")
     self.owm=OWM(config_private.openweather_key)
     self.connection=pymysql.connect(host=config_private.db_host,port=config_private.db_port,user=config_private.db_user,passwd=config_private.db_password,db=config_private.db_name)
     self.cursor=self.connection.cursor()
     self.log.info("Successfully initialized")
示例#4
1
def predict():
	# fetch the current forecast
	config = getConfig('config.ini')
	OWM_API_key = config.get('config', 'OWM_API_key').encode('ascii')
	OWM_location = config.get('config', 'OWM_location').encode('ascii')
	owm = OWM(OWM_API_key)
	fc = owm.daily_forecast(OWM_location, limit=3)
	f = fc.get_forecast()

	predictions = []
	for w in f:
		# Figure out if the sun is up(probably important)
		daytime = 'f'
		currTime = w.get_reference_time()
		sunriseTime = w.get_sunrise_time()
		sunsetTime = w.get_sunset_time()
		if(currTime > sunriseTime and currTime < sunsetTime):
			daytime = 't'
		result = powerProduction.query.filter_by(daytime='t', status=w.get_status())
		weatherData = []
		powerData = []
		for r in result:
			weatherData.append([r.cloudCover, r.windSpeed, r.humidity, r.pressure, r.temperature])
			powerData.append([r.powerLevel])
		
		# perform multivariate linear regression on the data to find the correlation between weather and power production
		model = linear_model.LinearRegression()
		model.fit(weatherData,powerData)

		cloudCover = w.get_clouds()
		windSpeed = 0
		humidity = w.get_humidity()
		pressure = w.get_pressure()['press']
		temperature = w.get_temperature(unit='celsius')['day']
		status = w.get_status()

		currentWeather = array([cloudCover, windSpeed, humidity, pressure, temperature])

		# use the regression model to generate production predictions based on the current forecast
		# print "Predicted power production: " + str(model.predict(currentWeather))
		predictions.append(model.predict(currentWeather))

	print "predictor run..."

	return predictions
示例#5
0
def get_weekly_weather_list():
    today = datetime.today().date()  #.strftime('%Y%m%d')
    today_day_index = today.weekday()
    weather_list = ['cloudy' for i in range(7)]
    openweather_key = "651e99c02e73a125832267efd3e2b11e"
    owm = OWM(openweather_key)
    fc = owm.three_hours_forecast('Korea')

    f = fc.get_forecast()
    lst = f.get_weathers()
    for weather in lst:

        date_str = weather.get_reference_time('date').strftime('%Y%m%d')
        date_ = datetime.strptime(date_str, '%Y%m%d').date()

        date_diff = date_ - today
        if today_day_index + date_diff.days > 6:
            break
        weather_list[today_day_index + date_diff.days] = str_match(
            weather.get_status())

    if weather_list[6] == 0:
        weather_list[6] = weather_list[5]

    return weather_list
示例#6
0
def stats():
    """ Returns last reading """
    temps_lst = []
    owm = OWM(OWM_APIKEY)
    fc = owm.three_hours_forecast('Berkeley,CA')
    f = fc.get_forecast()
    for weather in f:
        tm_stmp = datetime.fromtimestamp(
            weather.get_reference_time()).strftime('%Y-%m-%d %H:%M:%S')
        temp = 9 / 5 * (weather.get_temperature()['temp'] - 273.15) + 32
        humi = weather.get_humidity()
        dd = {'tm_stmp': tm_stmp, 'temp': temp, 'humid': humi}
        temps_lst.append(dd)
    with open('/home/pi/kindbot/app/logs/kindbot.log', 'rb') as fl:
        last_rd = fl.read()
    read_dict = eval(last_rd)
    try:
        alert = next(x for x in temps_lst if x['temp'] < 40 or x['temp'] > 85)
    except:
        alert = None
    lux = int(round(read_dict['Lumens'], -3))
    lux_sentence = lux_checker(lux)
    speech_text = "Last reading was taken at %s. The temperature is %s degrees Fahrenheit and humidity is at %s percent. " % (
        read_dict['Time'][:-3], read_dict['Temperature'],
        read_dict['Humidity']) + lux_sentence
    if alert:
        if alert['temp'] < 40:
            tt = 'cold.'
        elif alert['temp'] > 85:
            tt = 'hot.'
        date_a = alert['tm_stmp'].split(' ')[0]
        ddate = datetime.strptime(date_a, '%Y-%m-%d')
        date_alert = ddate.strftime("%A, %B %d")
        speech_text = speech_text + ' Heads up: ' + date_alert + ' will be ' + tt
    return statement(speech_text)
示例#7
0
    async def weatherCommand(self, ctx, query):
        try:
            owm = OWM(OWM_KEY)
            mgr = owm.weather_manager()

            observation = mgr.weather_at_place(query)
            w = observation.weather

            embed = discord.Embed(title=f'{query.capitalize()}')
            embed.add_field(
                name='Temp Low',
                value=f'{w.temperature("fahrenheit")["temp_min"]} °F')
            embed.add_field(
                name='Temp High',
                value=f'{w.temperature("fahrenheit")["temp_max"]} °F')
            embed.add_field(name='Humidity', value=f'{w.humidity}%')
            embed.add_field(
                name='Wind Speed',
                value=
                f'{round(float(w.wind(unit="miles_hour")["speed"]), 2)} mph')

            await ctx.send(embed=embed)
        except:
            await ctx.send(
                f':warning: {ctx.author.mention} There was an issue with your Openweathermap query. Please try again.'
            )
示例#8
0
def get_current_weather(code=None, coords=None):
    ''' Get the current weather for the given zipcode or coordinates.

    :param code: the zip code to find weather data about
    :type code: string
    :param coords: the coordinates for the data you want
    :type coords: 2-tuple

    :return: the raw weather object
    :type: json
    '''
    owm = OWM(loohoo_key)

    try:
        result = get_data_from_weather_api(owm, zipcode=code)
    except APICallTimeoutError:
        owm = OWM(loohoo_key)
    current = json.loads(
        result.to_JSON())  # the current weather for the given zipcode
    if code:
        current['Weather']['zipcode'] = code
    current['coordinates'] = current['Location']['coordinates']
    current['Weather']['instant'] = 10800 * (
        current['Weather']['reference_time'] // 10800 + 1)
    current['Weather']['time_to_instant'] = current['Weather'][
        'instant'] - current['Weather'].pop('reference_time')
    current.pop('Location')
    return current
def process_message(bot, u): #This is what we'll do when we get a message 
    #Use a custom keyboard 
    keyboard = [['Get Weather']] #Setting a Button to Get the Weather 
    reply_markup = ReplyKeyboardMarkup.create(keyboard) #And create the keyboard 
    if u.message.sender and u.message.text and u.message.chat: #if it is a text message then get it 
        chat_id = u.message.chat.id 
        user = u.message.sender.username
        message = u.message.text 
        print ( chat_id )
        print ( message )
        if message == 'Get Weather': #if the user is asking for the weather then we ask the location 
            bot.send_message(chat_id, 'please send me your location') 
        else: 
            bot.send_message(chat_id, 'please select an option', reply_markup=reply_markup).wait() #if not then just show the options
 
    elif u.message.location: #if the message contains a location then get the weather on that latitude/longitude 
        print ( u.message.location )
        chat_id = u.message.chat.id 
        owm = OWM(OWMKEY) #initialize the Weather API 
        obs = owm.weather_at_coords(u.message.location.latitude, u.message.location.longitude) #Create a weather observation 
        w = obs.get_weather() #create the object Weather as w 
        print(w) # <Weather - reference time=2013-12-18 09:20, status=Clouds> 
        l = obs.get_location() #create a location related to our already created weather object And send the parameters 
        status = str(w.get_detailed_status()) 
        placename = str(l.get_name()) 
        wtime = str(w.get_reference_time(timeformat='iso')) 
        temperature = str(w.get_temperature('celsius').get('temp'))
        wind = str(w.get_wind().get('speed'))
        bot.send_message(chat_id, 'Wind: '+wind+' at '+placename+' and temperature: '+ temperature+ 'C') #send the anwser
        bot.send_message(chat_id, 'please select an option', reply_markup=reply_markup).wait() #send the options again
    else: 
        print ( u )
        bot.send_message(chat_id, 'please select an option', reply_markup=reply_markup).wait() 
示例#10
0
def render_results():
    city = request.form['city']
    owm = OWM('55ab3b72ce60553c9d1a2cd9208b4e0e')
    mgr = owm.weather_manager()
    observation = mgr.weather_at_place(city)
    w = observation.weather
    temp = round(w.temperature('celsius')['temp'], 0)
    details = w.detailed_status
    if details == "mist" or details == "fog":
        icon = "fas fa-smog"
    elif details == "clear sky":
        icon = "fas fa-sun"
    elif details == "few clouds":
        icon = "fas fa-cloud-sun"
    elif details == "thunderstorm":
        icon = "fas fa-bolt"
    elif details == "snow":
        icon = "far fa-snowflake"
    elif details == "rain":
        icon = "fas fa-cloud-rain"
    elif details == "shower rain":
        icon = "fas fa-cloud-showers-heavy"
    else:
        icon = "fas fa-cloud"

    return render_template('results.html',
                           city=city,
                           temp=temp,
                           details=details,
                           icon=icon)
示例#11
0
def process_message(msg):
    keyboard = [['Get Weather']]
    reply_markup = ReplyKeyboardMarkup.create(keyboard)

    chat_id = msg['chat']['id']
    message = msg['text']
    #    <command> <argument>
    #   weather accra,ghana
    if re.match(r'hi|hello', message.lower()):
        bot.sendMessage(chat_id, 'Hi! Am Sunny , how may i help you ?')
    elif re.match(r'time', message.lower()):
        print(message)
        bot.sendMessage(chat_id, str(now.hour) + str(":") + str(now.minute))
    elif re.match(r'weather', message.lower()):
        words = message.lower().split()
        location = words[1] + ", " + words[2]

        print(chat_id)
        print(message)
        owm = OWM(OWMKEY)
        obs = owm.weather_at_place(location)
        w = obs.get_weather()
        l = obs.get_location()
        status = str(w.get_detailed_status())
        placename = str(l.get_name())
        wtime = str(w.get_reference_time(timeformat='iso'))
        temperature = str(w.get_temperature('celsius').get('temp'))

        bot.sendMessage(
            chat_id, 'Weather Status: ' + status + ' At ' + placename + ' ' +
            wtime + ' Temperature: ' + temperature + 'C')
    else:
        return bot.sendMessage(chat_id, 'please select an option')
示例#12
0
    def action(msg):
        from pyowm import OWM
        from dotenv import load_dotenv
        load_dotenv()

        split_text = msg.split(' ')
        location = split_text[split_text.index('in') + 1]

        try:
            key = os.getenv('OW_API_KEY')
            owm = OWM(key)  # You MUST provide a valid API key

        except Exception as e:
            logging.warning(str(e))
            logging.warning(
                'Get you OpenWeather API key here: https://home.openweathermap.org/users/sign_up'
                '\n at save it in your `.env` using `OW_API_KEY`')

        # Search for current weather in London (Great Britain)
        # TODO derive country acro from location and not hard code `AT`
        observation = owm.weather_at_place(f'{location},AT')

        w = observation.get_weather()

        status = w.get_status()
        # TODO check actual unit of temperature - Kelvin, thus `- 273.15` looks odd
        temperature = w.get_temperature().get('temp') - 273.15
        logging.msg(
            f"{np_round(temperature, 1)}°C - {ShowWeather.emojis.get(status, status)}"
        )
        return f"looks like {status} with {str(np_round(temperature, 1))} degrees Celcius."
示例#13
0
def timed_task1():
    global hours_no_water, irrigation_cnt, irrigation_timer, NoFault, irrigation_manual
    # use pyowm to get weather where I am
    API_key = 'a3f08180a153e131e0e13d9d30a7c315'
    owm = OWM(API_key)
    # sett locale to my garden
    while NoFault:
        if irrigation_auto:
            # check weather forecast, see if there's any rain
            print("T1> Checking weather")
            obs = owm.weather_at_coords(54.92, -1.74)
            w = obs.get_weather()
            rain_str = w.get_detailed_status()
            print('T1>', rain_str)
            if 'rain' in rain_str:
                print('T1> reset counter')
                hours_no_water = 0
            else:
                print('T1> increment counter')
                hours_no_water += 1
            # run irrigation if required
            if (hours_no_water >= 60):
                print('T1> Turn on irrigation')
                #turn on solenoid
                O2.on()
                irrigation_timer.reset()
                irrigation_cnt += 1
                sleepMin(15)
                #solenoid off
                O2.off()
                hours_no_water = 0
            # wait an hour
            sleepMin(60)
示例#14
0
def get_current_weather(city_id=6553047):
    # Search for current weather in city(country)
    owm = OWM(API_key)
    observation = owm.weather_at_id(city_id)
    w = observation.get_weather()
    # print(w)

    weather = {}
    # WEATHER DETAILS
    wind = w.get_wind()
    wind = wind_analysieren(wind)
    temperature = w.get_temperature('celsius')
    temperature = temperature.get('temp')
    rain = w.get_rain()
    timestamp = w.get_reference_time()
    time = timestamp_to_localtime(timestamp)
    icon = w.get_weather_icon_name()

    # daten einspeichern
    weather['time'] = time
    weather['icon'] = icon
    weather['temperature'] = temperature
    weather['wind'] = wind
    weather['rain'] = rain

    return weather
示例#15
0
    def do_POST(self):
        global password  #import password
        print("GET triggered")

        if not self.headers['Authorization'] == password:  # security check
            print("Wrong password")
            return

        #load info from content headern
        req = (self.rfile.read(int(
            self.headers['content-length']))).decode('utf-8')
        req = json.loads(req)

        location = 'Sjöbo,SE'  #location of weather station
        owm = OWM(
            'e2bc44778d5f1c9c0cdc7177e10c2e8e')  #api key for open weather api

        #init and get an wether observation
        mgr = owm.weather_manager()
        observation = mgr.weather_at_place(location)
        w = observation.weather

        time = req["metadata"]["time"]
        time = time.replace("T", " ")
        time = time.replace("Z", "")
        mh.input_data(req["dev_id"], time,
                      w.temperature('celsius')['temp'],
                      w.wind()['speed'], w.humidity, w.clouds,
                      req["payload_fields"]["sensor_trigger"])
示例#16
0
def index(request):
    events = CalendarItem.objects.filter(date__range=[datetime.date.today(), (datetime.date.today() + timedelta(days=5))])
    events = events.order_by("date")
    i = 0
    while events.count() < 5:
        iday = datetime.date.today() + timedelta(days=i)
        try:
            if events[i].day != iday.strftime("%A"):
                CalendarItem.objects.create(name="", date=iday, day=iday.strftime("%A"))
            i = i + 1
        except:
            CalendarItem.objects.create(name="", date=iday, day=iday.strftime("%A"))
            events = CalendarItem.objects.filter(
                date__range=[datetime.date.today(), (datetime.date.today() + timedelta(days=5))])
            events = events.order_by("date")
            i = 0

    events = CalendarItem.objects.filter(date__range=[datetime.date.today(), (datetime.date.today() + timedelta(days=5))])
    events = events.order_by("date")

    owm = OWM(API_key)
    obs = owm.weather_at_id(2078025)
    w = obs.get_weather()
    weather = w.get_weather_code()
    temp = w.get_temperature('celsius')
    temp = round(temp['temp'], 0)
    greeting = random.choice(Greetings.objects.all())
    return render(request, 'Main/index.html', {'greeting': greeting, 'weather':weather, 'temp':temp, 'events':events})
示例#17
0
def structure(command):
    if 'open' in command:
        reg_ex = re.search('open (.+)', command)
        url = 'https://www.'
        if reg_ex:
            domain = reg_ex.group(1)
            domain.replace(' ', '')
            url = f'{url}{domain}'
            webbrowser.open_new_tab(url)
        else:
            pass
    elif 'weather' in command:
        reg_ex = re.search('weather in (.*)', command)
        if reg_ex:
            city = reg_ex.group(1)
            owm = OWM(API_key='ab0d5e80e8dafb2cb81fa9e82431c1fa')
            obs = owm.weather_at_place(city)
            w = obs.get_weather()
            sky = w.get_status()
            tem = w.get_temperature(unit='fahrenheit')
            response.regis(
                f'''It is {sky} in {city} and the temperature is {int(tem['temp'])} degrees fahrenheit.'''
            )
    elif 'time' in command:
        now = datetime.datetime.now()
        response.regis(f'The time is {(now.hour - 12)} {now.minute}')
示例#18
0
def update_forecast():
    API_key = 'ffdb44d857dd60cbdc3016e1ff59536b'
    owm = OWM(API_key)
    fc = owm.three_hours_forecast('Garlate,it')
    f = fc.get_forecast()
    f_time = []
    f_temp = []
    f_rain = []

    for weather in f:
        f_temp.append(weather.get_temperature(unit='celsius')['temp'])
        f_time.append(weather.get_reference_time('iso')[:19])
        if weather.get_status() == 'Rain':
            f_rain.append(weather.get_rain()['3h'])
        else:
            f_rain.append(0.0)

    #df = pd.DataFrame(f_temp,index=f_time,columns=['temp'])
    d = {'temp': f_temp, 'rain': f_rain, 'time': f_time}
    df = pd.DataFrame(data=d)

    fname = os.environ["WSDATAPATH"] + "/forecast.csv"
    df.to_csv(fname, sep=',', decimal='.', index=False)
    subprocess.call(
        'head -n 9 forecast.csv | tail -n 8 >> one_day_forecast.csv',
        shell=True)
    return
示例#19
0
def weather_get():
    # setup
    owm = OWM(OWM_API_KEY)
    obs = owm.weather_at_coords(29.700389, -95.402497)
    htown_weather = obs.get_weather()

    # weather
    temp_results = htown_weather.get_temperature('fahrenheit')
    rain = htown_weather.get_rain()
    wind = htown_weather.get_wind()['speed']
    condition = htown_weather.get_detailed_status()

    # UV
    uvi = owm.uvindex_around_coords(29.700389, -95.402497)
    risk = uvi.get_exposure_risk()

    output = {
        'temp': temp_results,
        'rain': rain,
        'wind': wind,
        'condition': condition,
        'risk': risk
    }

    return output
示例#20
0
文件: run.py 项目: netsirkdmb/cs496
def weather():
    # create OWM object
    API_key = '3ca51794f7789141f0525a05d80a43b9'
    owm = OWM(API_key)

    theCity = "Seattle"
    theState = "WA"
    weatherCityState = theCity + ", " + theState
    weatherLocation = theCity + ",US"

    # get currently observed weather for Seattle, WA, US
    obs = owm.weather_at_place(weatherLocation)

    # get weather object for current Seattle weather
    w = obs.get_weather()

    # get current weather status and temperature in fahrenheit
    currStatus = w.get_detailed_status()
    tempF = w.get_temperature('fahrenheit')["temp"]

    # query the daily forcast for Seattle, WA, US, for the next 5 days
    fc = owm.daily_forecast('Seattle,US', limit=5)

    # get a forcaster object
    f = fc.get_forecast()

    return render_template('templateWeather.html', theLocation=weatherCityState, currStatus=currStatus, theTemp=tempF, forecast=f,
                           title="Weather", arrow=arrow)
示例#21
0
def assistant(command):

    #  conversation
    if 'hello' in command:
        t = datetime.datetime.now()
        if t.hour < 12:
            greet = "Good Morning"
        elif t.hour > 12 and t.hour < 18:
            greet = "Good Afternoon"
        else:
            greet = "Good Evening"

        reqRes.botResponse("{}! What can I do for you?".format(greet))

    elif 'shutdown' in command:
        reqRes.botResponse("Enjoy your day!")
        exit()

#   task 1 - Open website
    elif "open" in command:
        reg_ex = re.search('open (.+)', command)
        domain = reg_ex.group(1)
        if reg_ex:
            url = 'https://www.' + domain
            webbrowser.open(url)
            reqRes.botResponse("Opening {}".format(domain))
        else:
            pass
#   task 2 - Weather functionality
    elif "current weather" in command:
        reg_ex = re.search('current weather in (.+)', command)
        if reg_ex:
            city = reg_ex.group(1)
            owm = OWM('043c95bd84b2bbcdcf7404f634788f85')
            mgr = owm.weather_manager()
            obs = mgr.weather_at_place(city)
            w = obs.weather
            s = w.status()
            t = w.temperature('celsius')
            reqRes.botResponse(
                'Current weather in %s is %s. The maximum temperature is %0.2f and the minimum temperature is %0.2f degree celcius'
                % (city, s, t['temp_max'], t['temp_min']))

    elif "time" in command:
        t = datetime.datetime.now()
        h = t.hour
        m = t.minute
        s = t.second
        res = 'The time is {} hours {} minutes and {} seconds.'.format(h, m, s)
        print(res)
        reqRes.botResponse(res)

    elif "date" in command:
        t = datetime.datetime.now()
        d = t.day
        m = t.month
        y = t.year
        res = 'Today is {}, {}, {}.'.format(d, m, y)
        print(res)
        reqRes.botResponse(res)
示例#22
0
class Weather:
    def __init__(self, api_key=None, metric_temp=None, metric_wind=None):
        self.manager = OWM(api_key or WX_API_KEY).weather_manager()
        self.metric_temp = metric_temp or WX_METRIC_TEMP
        self.metric_wind = metric_wind or WX_METRIC_WIND

    def get_weather_data(self, weather):
        return {
            "max": weather.temperature(self.metric_temp)["temp_max"],
            "min": weather.temperature(self.metric_temp)["temp_min"],
            "temp": weather.temperature(self.metric_temp)["temp"],
            "wind": weather.wind(self.metric_wind)["speed"],
            "status": weather.detailed_status,
            "sun_rise": weather.srise_time,
            "sun_set": weather.sset_time,
            "rain": weather.rain,
            "time": weather.ref_time,
        }

    def current(self, location):
        observation = self.manager.weather_at_place(location)
        weather = observation.weather

        result = self.get_weather_data(weather)
        result["location"] = f"{observation.location.name} {observation.location.country}"

        return result

    def forecast(self, location, interval="3h"):
        forecaster = self.manager.forecast_at_place(location, interval)
        location = f"{forecaster.forecast.location.name} {forecaster.forecast.location.country}"
        return [
            {**self.get_weather_data(weather), **{"location": location}} for weather in forecaster.forecast.weathers
        ]
示例#23
0
def getWeatherOutside():
    owm = OWM(ApiKey)
    observation = owm.weather_manager().weather_at_place(city)
    w = observation.weather
    temperature = w.temperature('celsius')['temp']
    humidity = w.humidity
    return temperature, humidity
示例#24
0
    def weather_extreme(cur_bot, location='Rolla'):
            # Set API Key
        API_key = '0f5e7a1e7682ce843b443549718b5f95'
        owm = OWM(API_key)

        # Returns an "observation" of weather data (NOT A FORECAST)
        obs = owm.weather_at_place(location)
            # Gets actual weather data
        w = obs.get_weather()
        temp_f_dict = w.get_temperature('fahrenheit') #this is a dictionary of fahrenheit values

            # find the high for the day in the temperature dictionary
        temp_high = 0
        for key in temp_f_dict:
            if key == 'temp_max':
                temp_high = temp_f_dict[key]
            # find the low for the day in the temperature dictionary
        temp_low = 0
        for key in temp_f_dict:
            if key == 'temp_min':
                temp_low = temp_f_dict[key]

        l = obs.get_location()
        location_name = l.get_name()
        print("User input location: " + location)
        print("The object location: " + location_name)

        cur_bot.post("High: " + str(temp_high) + "°F\nLow: " + str(temp_low) + "°F")
示例#25
0
class OWMLink:
    def __init__(self, instance):
        self.instance = instance
        self.link = OWM(API_key, language=language_str)  # setup OpenWeatherMap connection
        self.keep_running = True

    def run(self):
        con_error_cnt = 0
        while self.keep_running:
            print 'connecting to weather'
            try:
                owm_is_online = self.link.is_API_online()
            except:  # api_call_error.APICallError
                con_error_cnt += 1
                print 'connection to OWM API failed'
                if con_error_cnt < 10:
                    print 'will try again in 2 seconds'
                    time.sleep(2)  # wait 2 seconds before trying it again
                    continue
                else:
                    # quit if connection could not be est. 10 times in a row
                    print 'OWM API seems to be offline, quitting'
                    break
            con_error_cnt = 0  # reset connection error counter if connection was successful
            if owm_is_online:
                obs = self.link.weather_at_place(location_str)
                App.get_running_app().owm_thread_weather = obs.get_weather()
            else:
                App.get_running_app().owm_thread_weather = None
                print('OWM service is offline')
            time.sleep(owm_fetch_sleep_time)  # should be last statement in while loop
示例#26
0
def check_weather(api_key="c84c2f255787c9dfc3d1c8b3795e4686",
                  ):  # use a public api key in default
    # this method gets the actual data from openweathermap.org
    print("Checking weather in Tel Aviv, Israel...")
    output = {}
    owm = OWM(api_key)

    if owm.is_API_online():
        print("OpenWeatherMap API is ONLINE!")
        country = "Israel"
        city = "Tel Aviv"
        print("City is " + city)
        print("Country is " + country)
        obs = owm.weather_at_place(city + "," + country)

        w = obs.get_weather()
        output["clouds"] = w.get_clouds()
        output["rain"] = w.get_rain()
        output["snow"] = w.get_snow()
        output["wind"] = w.get_wind()
        output["humidity"] = w.get_humidity()
        output["pressure"] = w.get_pressure()
        output["temperature"] = w.get_temperature("celsius")
        output["status"] = w.get_detailed_status()
        output["sunrise"] = w.get_sunrise_time()
        output["sunset"] = w.get_sunset_time()
    else:
        print("OWM API is OFFNLINE, FAILED")
        output["status"] = "FAILED"
    return json.dumps(output, indent=3)
示例#27
0
def get_weather_in_x_hours(hours, city_id=6553047):
    # WIND analyisieren (6h)
    speicher = {}
    owm = OWM(API_key)
    fc = owm.three_hours_forecast_at_id(city_id)
    # f = fc.get_forecast()
    # fc_lst = f.get_weathers()
    time_six_hours = datetime.now() + timedelta(hours=hours)
    weather_in_hours = fc.get_weather_at(time_six_hours)

    wind_in_hours = weather_in_hours.get_wind()
    wind_in_hours = wind_analysieren(wind_in_hours)

    time_in_hours = weather_in_hours.get_reference_time()
    time_in_hours = timestamp_to_localtime(time_in_hours)

    rain_in_hours = weather_in_hours.get_rain()
    temperature_in_hours = weather_in_hours.get_temperature(unit='celsius')
    temperature_in_hours = temperature_in_hours.get('temp')
    icon_in_hours = weather_in_hours.get_weather_icon_name()

    # WIND | Time | Rain | Temperature | icon  --> SPEICHER
    speicher['time'] = time_in_hours
    speicher['icon'] = icon_in_hours
    speicher['temperature'] = temperature_in_hours
    speicher['wind'] = wind_in_hours
    speicher['rain'] = rain_in_hours

    return speicher
示例#28
0
 def __init__(self,OWMKEY):
     self.owm = OWM(OWMKEY)
     self.weather_dict = {}   #value voor in dictionary
     self.temp = ""
     self.weather = ""
     self.weather_code = 0
     self.prev_loc = ""
示例#29
0
 def __init__(self, city):
     owm = OWM(pyowm_key)
     mgr = owm.weather_manager()
     try:
         observation = mgr.weather_at_place(city)
     except InvalidSSLCertificateError:
         self.status = None
     except APIResponseError:
         self.status = None
     except NotFoundError:
         self.status = 1
     else:
         self.status = 2
         weather = observation.weather
         self.detailed_status = gettext(
             weather.detailed_status.capitalize())
         temperature = weather.temperature('celsius')
         self.temperature = round(temperature['temp'], 1)
         self.wind = weather.wind()['speed']
         self.humidity = weather.humidity
         self.heat_index = weather.heat_index
         self.clouds = weather.clouds
         self.city = city
         self.weather_icon = url_for(
             'static', filename=f'weather_icons/{weather.status}.png')
示例#30
0
    def wrapper_load_config(string, entities):
        payload = dict()
        payload["string"] = string
        payload["entities"] = entities

        api_key = utils.config("api_key")
        pro = utils.config("pro")
        payload["temperature_units"] = utils.config("temperature_units")
        payload["wind_speed_units"] = utils.config("wind_speed_units")

        if ((payload["temperature_units"] != "celsius")
                and (payload["temperature_units"] != "fahrenheit")):
            return utils.output("end", "invalid_temperature_units",
                                utils.translate("invalid_temperature_units"))

        if payload["wind_speed_units"] == "meters per seconds":
            payload["wind_speed_units_response"] = payload["wind_speed_units"]
            payload["wind_speed_units"] = "meters_sec"
        elif payload["wind_speed_units"] == "miles per hour":
            payload["wind_speed_units_response"] = payload["wind_speed_units"]
            payload["wind_speed_units"] = "miles_hour"
        else:
            return utils.output("end", "invalid_wind_speed_units",
                                utils.translate("invalid_wind_speed_units"))

        if pro:
            payload["owm"] = OWM(api_key, subscription_type="pro")
        else:
            payload["owm"] = OWM(api_key)

        return func(payload)
示例#31
0
def get_weather(coords, date=None) -> Weather:
    """
    Retorna um objeto da PyOWM, para uso interno da classe.
    Pode resultar em um NotFoundError da PyOWM também.
    """
    global __owm
    if not __owm:
        __owm = OWM(
            API_key=owm_token,
            config_module='tele_weather_bot.weather.configuration'
            # essa configuração acima muda a linguagem para 'pt' e
            # adiciona um cache simples pra tentar reduzir os requests
        )

    if not __owm.is_API_online():
        raise APICallError

    if date and (date - datetime.now()) > timedelta(hours=3):
        fc = __owm.three_hours_forecast_at_coords(coords['lat'], coords['lng'])
        observation = fc.get_weather_at(date)
    else:
        observation = __owm.weather_at_coords(coords['lat'],
                                              coords['lng']).get_weather()

    return observation
示例#32
0
class OpenWeatherMapModel:
    def __init__(self, api_key: str, city_id: int):
        self.owm = OWM(api_key)
        self._city_id = city_id
        self._unit = 'celsius'

    @property
    def city_id(self):
        return self._city_id

    @city_id.setter
    def city_id(self, city_id: int):
        self._city_id = city_id

    @property
    def temperature_unit(self):
        return self._unit

    @temperature_unit.setter
    def temperature_unit(self, unit: str):
        assert unit == 'fahrenheit' or unit == 'celsius'
        self._unit = unit

    def _parse_weather(self, weather):
        temperature = weather.get_temperature(unit=self.temperature_unit)
        humidity = weather.get_humidity()
        weather_code = weather.get_weather_code()
        return (weather_code,
                temperature.get('temp_min', temperature.get('min')),
                temperature.get('temp_max', temperature.get('max')), humidity)

    def get_current_weather(self):
        """
        Get the current weather data
        :return: Tuple of weather code, temperature range, and humidity
        """
        try:
            obs = self.owm.weather_at_id(self.city_id)
            weather = obs.get_weather()
            return self._parse_weather(weather)
        except pyowm.exceptions.api_call_error.APICallTimeoutError:
            return 0, 0, 0, 0

    def get_daily_forecast(self, limit=14, include_today=False):
        """
        Get a list of forecasts
        :param limit: The max number of forecasts to get
        :param include_today: whether include today in the forecast
        :return: list of tuples of weather code, temperature range and humidity
        """
        forecaster = self.owm.daily_forecast_at_id(self.city_id, limit=limit)
        weathers = forecaster.get_forecast().get_weathers()
        today = datetime.datetime.now().date()
        if not include_today:
            weathers = filter(
                lambda weather: not (weather.get_reference_time(
                    timeformat='date') == today), weathers)
        return list(map(lambda weather: self._parse_weather(weather),
                        weathers))
    def get_forecast(self, lat=45.523, lng=-73.581, days=4):
        owm = OWM(owm_key)

        self.lat = lat
        self.lng = lng
        self.days = days

        #if we want to use current weather
        if days == 0:
            fc = owm.weather_at_coords(self.lat, self.lng)
            w = fc.get_weather()
            self.T = w.get_temperature('celsius')['temp']
            self.rain = 1 if not w.get_rain() else 0
            self.forecast = (self.T, self.rain)

        #if we want to use weather forecast
        else:
            #Get weather forecast over the next five days, at 3h intervals
            fc = owm.three_hours_forecast_at_coords(self.lat, self.lng)

            #Get tempreature forecast and weather status at 12h and 15h (local time) over the next four days
            #Get the timezone
            tf = timezonefinder.TimezoneFinder()
            timezone_str = tf.certain_timezone_at(lat=self.lat, lng=self.lng)

            #Get the current local time
            self.clt = datetime.now()

            #Create a list of local times for which we want a forecast
            forecast_wanted = [
                self.clt + timedelta(days=i) for i in range(1, self.days + 1)
            ]
            list_of_forecast_wanted = [i.replace(hour=12) for i in forecast_wanted] + \
            [i.replace(hour=15) for i in forecast_wanted]

            #Change from local time to utc
            tmz = timezone(timezone_str)
            list_of_forecast_wanted = [
                tmz.localize(i).astimezone(timezone('UTC'))
                for i in list_of_forecast_wanted
            ]

            #Get the temperature forecast and average temperature
            temperature_forecast = [
                fc.get_weather_at(i).get_temperature('celsius')['temp']
                for i in list_of_forecast_wanted
            ]
            self.average_forecasted_T = np.mean(temperature_forecast)

            #See if it forecasts rain or not (0-->no rain, 1-->rain)
            rain_forecast = [
                1 if fc.will_be_rainy_at(i) else 0
                for i in list_of_forecast_wanted
            ]

            self.rain = 1 if float(
                np.sum(rain_forecast)) / len(rain_forecast) >= 0.5 else 0

            self.forecast = (self.average_forecasted_T, self.rain)
示例#34
0
def weather_command_message(message):
    if str(message.text)[:8] == '/weather':
        city = str(message.text)[9:]
        city = str(city)
        if city == "":
            city = 'Москва'
        morph = pymorphy2.MorphAnalyzer()
        counties = morph.parse(city)[0]
        gent = counties.inflect({'loct'})
        gent_new = gent.word
        gent_correct = gent_new.capitalize()
        config_dict = get_default_config()
        config_dict['language'] = 'ru'
        owm = OWM('0d16f6ffb7d46c30c1202a765e2cb0fc', config_dict)
        mgr = owm.weather_manager()
        observation = mgr.weather_at_place(city)
        w = observation.weather
        cloud = str(w.detailed_status)
        clouds = str(w.clouds)
        temp = w.temperature('celsius')['temp']
        temperature = str(temp).rsplit(".")[0]
        weather_message = (f'Сейчас в {gent_correct} {temperature} °C\n'
                           f'Небо затянуто на {clouds}%, {cloud}')
        bot.send_message(message.from_user.id, weather_message)
    elif str(message.text)[:6] == '/covid':
        bot.send_message(message.from_user.id,
                         "Пожалуйста, подождите, собираю статистику...")
        country = str(message.text)[7:]
        country = str(country)
        if country == "":
            country = 'россия'
        translator = Translator(from_lang="ru", to_lang="en")
        translation = translator.translate(country)
        morph = pymorphy2.MorphAnalyzer()
        counties = morph.parse(country)[0]
        gent = counties.inflect({'gent'})
        gent_new = gent.word
        gent_correct = gent_new.capitalize()
        covid = Covid(source="worldometers")
        country_cases = covid.get_status_by_country_name(
            translation)['new_cases']
        if country_cases == 0:
            country_cases = 'Статистика обновляется. Попробуйте заново через несколько часов.'
        else:
            country_cases = '+' + str(country_cases)
        confirmed_country_cases = covid.get_status_by_country_name(
            translation)['confirmed']
        deaths_country_cases = covid.get_status_by_country_name(
            translation)['deaths']
        covid_message = (f'Статистика для {gent_correct}:\n'
                         f'Всего заболевших за сутки: {country_cases}\n'
                         f'Всего случаев: {confirmed_country_cases}\n'
                         f'Зафиксировано смертей: {deaths_country_cases}')
        bot.send_message(message.from_user.id, covid_message)
    else:
        bot.send_message(
            message.from_user.id,
            "Я пока что не знаю, что мне на это ответить. Пожалуйста, пропиши команду /help"
        )
示例#35
0
 def __init__(self, app):
     self.app = app
     api_key = "b52881efed55c850de4de596b8a001b7"
     self.owm = OWM(api_key)
     self.min_old = -1
     self.weather = 0
     self.page = 1
     self.i = 0
示例#36
0
def get_data(key: str):
    owm = OWM(key)
    if owm.is_API_online:
        weather_data = owm.weather_at_id(CITY_ID).get_weather()
        download_img(
            f"http://openweathermap.org/img/wn/{weather_data.get_weather_icon_name()}@2x.png"
        )
        return weather_data
示例#37
0
def GetWeather():
    owm = OWM(api_key)
    obs = owm.weather_at_place(location)  
    w = obs.get_weather()
    weather = {}
    weather['clouds'] = w.get_clouds()
    weather['rain'] = w.get_rain()
    weather['wind'] = w.get_wind()
    weather['humidity'] = w.get_humidity()
    weather['temp'] = w.get_temperature('fahrenheit')
    print(weather)
    return weather
示例#38
0
文件: podaga.py 项目: Regaerd/Podaga
    def __init__(self, stdscr, args=None):
        self.stdscr = stdscr
        self.owm = OWM(API_key=args.api_key)

        self.find_location()
        self.location_name = "{}, {}".format(self.location['city'], self.location['region_name'])
        # self.loc = self.owm.weather_at_coords(self.location['latitude'], self.location['longitude'])
        self.temp_unit = args.temp_unit
        self.temp_symbol = self.temp_unit[0].upper()
        self.forecast = None
        self.spinner = Spinner(Spin1)
        self.bar_animation = 1
        self.last_update = None
        self.verbose = False
        self.error = ""

        try: # needed for terminals that don't support all color options
            for i in range(256):
                curses.init_pair(i+1, i, -1)
                self.color_range = i
        except:
            pass

        self.color_pri = curses.color_pair(2) | curses.A_BOLD
        self.color_sec = curses.color_pair(4) | curses.A_BOLD
        self.color_ext = curses.color_pair(5) | curses.A_BOLD

        self.draw_height = 2
        self.draw_width = 0 # generated by view_resized
        self.tries = 0
        self.view_resized()
示例#39
0
 def get_weather(self, location="Lawrence, KS"):
     _owm_api_key_ = cf.get("owm", "API_KEY")
     owm = OWM(API_key=_owm_api_key_)
     # loc = location.replace(" ", ",")
     # print loc
     obs = owm.weather_at_place(location)
     # print obs
     w = obs.get_weather()
     print(w.get_temperature("fahrenheit"))
     print(w.get_detailed_status())
     stats = [w.get_temperature("fahrenheit"), w.get_detailed_status()]
     words = (
         "The temperature in fahrenheit is "
         + str(stats[0]["temp"])
         + " and it is going to be "
         + stats[1]
     )
     return words
示例#40
0
class Weather(object):
    """ Weather class for managing owm api. """
    def __init__(self, area='Austin,tx'):
        """ Init function for class. """
        self._owm = OWM('3d0b141357a6842ab0f3a42a9192a836')
        self.city = None
        self.country = None
        self.latitude = 0.00
        self.longitude = 0.00
        self.status = None
        self.wind_speed = 0.0
        self.humidity = 0
        self.pressure = 0
        self.temp = 0
        self.min_temp = 0
        self.max_temp = 0
        self._populate_weather(area)

    def to_json(self):
        """ Get weather data as json. """
        weather_data = dict()
        weather_data['location'] = dict()
        weather_data['weather'] = dict()
        weather_data['weather']['temperature'] = dict()
        weather_data['location']['coordinates'] = dict()
        weather_data['weather']['status'] = self.status
        weather_data['weather']['wind_speed'] = self.wind_speed
        weather_data['weather']['humidity'] = self.humidity
        weather_data['weather']['pressure'] = self.pressure
        weather_data['weather']['temperature']['temp'] = self.temp
        weather_data['weather']['temperature']['min_temp'] = self.temp
        weather_data['weather']['temperature']['max_temp'] = self.temp
        weather_data['location']['city'] = self.city
        weather_data['location']['country'] = self.country
        weather_data['location']['coordinates']['latitude'] = self.latitude
        weather_data['location']['coordinates']['longitude'] = self.longitude
        return dumps(weather_data)

    def _populate_weather(self, location='Austin,tx'):
        """ Populate weather class. """
        observation = self._owm.weather_at_place(location)
        weather = observation.get_weather()
        obs_json = observation.to_JSON()
        obs = loads(obs_json)
        self.country = obs['Location']['country']
        self.latitude = obs['Location']['coordinates']['lat']
        self.longitude = obs['Location']['coordinates']['lon']
        self.city = obs['Location']['name']
        self.status = obs['Weather']['status']
        self.wind_speed = weather.get_wind()['speed']
        self.humidity = weather.get_humidity()
        self.pressure = weather.get_pressure()['press']
        self.temp = weather.get_temperature('fahrenheit')['temp']
        self.min_temp = weather.get_temperature('fahrenheit')['temp_min']
        self.max_temp = weather.get_temperature('fahrenheit')['temp_max']
示例#41
0
文件: weather.py 项目: bear/tenki
class Weather():
    def __init__(self, api_key, keyBase, dbRedis):
        self.pyOWM   = OWM(api_key)
        self.db      = dbRedis
        self.keyRoot = '%sweather-' % keyBase

    def clear(self, location):
        key = '%s%s' % (self.keyRoot, location)
        self.db.delete(key)

    def load(self, location):
        """Given a location, return any cached value

        location: string
        returns:  dictionary
        """
        key   = '%s%s' % (self.keyRoot, location)
        value = self.db.get(key)

        if value is not None:
            return json.loads(value)

    def save(self, location, value, expires=300):
        """Save the weather dictionary for the given location

        location: string
        value: dictionary
        """
        key = '%s%s' % (self.keyRoot, location)
        self.db.set(key, json.dumps(value))
        self.db.expire(key, expires)

    def OpenWeatherMap(self, location):
        """Call OpenWeatherMap to retrive the weather for the given location

        location: string
        returns:  dictionary
        """
        w = self.pyOWM.weather_at_place(location).get_weather().to_JSON()
        return json.loads(w)

    def get(self, location):
        """Get the current weather for the given location

        location: string
        returns:  dictionary
        """
        w = self.load(location)
        if w is None:
            w = self.OpenWeatherMap(location)
            self.save(location, w)
        return w
示例#42
0
 def __init__(self, area='Austin,tx'):
     """ Init function for class. """
     self._owm = OWM('3d0b141357a6842ab0f3a42a9192a836')
     self.city = None
     self.country = None
     self.latitude = 0.00
     self.longitude = 0.00
     self.status = None
     self.wind_speed = 0.0
     self.humidity = 0
     self.pressure = 0
     self.temp = 0
     self.min_temp = 0
     self.max_temp = 0
     self._populate_weather(area)
示例#43
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """ Get the OpenWeatherMap sensor. """

    if None in (hass.config.latitude, hass.config.longitude):
        _LOGGER.error("Latitude or longitude not set in Home Assistant config")
        return False

    try:
        from pyowm import OWM

    except ImportError:
        _LOGGER.exception(
            "Unable to import pyowm. "
            "Did you maybe not install the 'PyOWM' package?")

        return None

    SENSOR_TYPES['temperature'][1] = hass.config.temperature_unit
    unit = hass.config.temperature_unit
    owm = OWM(config.get(CONF_API_KEY, None))
    obs = owm.weather_at_coords(hass.config.latitude, hass.config.longitude)

    if not owm:
        _LOGGER.error(
            "Connection error "
            "Please check your settings for OpenWeatherMap.")
        return None

    dev = []
    for variable in config['monitored_variables']:
        if variable['type'] not in SENSOR_TYPES:
            _LOGGER.error('Sensor type: "%s" does not exist', variable['type'])
        else:
            dev.append(OpenWeatherMapSensor(variable['type'], obs, unit))

    add_devices(dev)
示例#44
0
class Weather(PluginBase):
    def __init__(self):
        self._owm = OWM(os.environ['OWM_API_KEY'])

    def execute(self, args):
        if len(args) != 1:
            raise ValueError('wrong number of arguments are given')

        location = args[0]

        result = ''
        for weather in self._owm.daily_forecast(location, 7).get_forecast():
            result += '{:s} {:s}\n'.format(weather.get_reference_time('iso'), weather.get_status())

        return result

    def help(self):
        return 'location\n' \
               'Print current weather observations and forecast'
示例#45
0
    def __init__(self, parent=None):
        super(MyMainGui, self).__init__(parent)
        self.setupUi(self)
        app.setStyle(QStyleFactory.create('Plastique'))

        API_key = '1330050f05c5c2c1f05e678136d1ebc2'
        self.owm = OWM(API_key)

        # get a list of countries and alpha2 codes
        self.countries_list, self.alpha2_code_list = countries_list_and_code()

        self.comboBox_country.addItems(self.countries_list)
        self.toolButton_search.clicked.connect(self.search_city)
        self.lineEdit_city.returnPressed.connect(self.search_city)
        self.toolButton_next.clicked.connect(self.next_page_of_three_hour_display)
        self.toolButton_previous.clicked.connect(self.previous_page_of_three_hour_display)

        self.toolButton_previous.setDisabled(True)
        self.three_hour_display_page_number = 1

        # disable the line below if you don't want to load weather for Berlin at start up
        self.initialize_display()
示例#46
0
 def __init__(self, instance):
     self.instance = instance
     self.link = OWM(API_key, language=language_str)  # setup OpenWeatherMap connection
     self.keep_running = True
示例#47
0
class WeatherForecastUpdaterThread(LoopingThread):

    def initialize(self):
        self.log=LoggerFactory.get_file_logger(config.log_filename,"WeatherForecastUpdaterThread",config.log_level)
        self.log.info("Initializing")
        self.owm=OWM(config_private.openweather_key)
        self.connection=pymysql.connect(host=config_private.db_host,port=config_private.db_port,user=config_private.db_user,passwd=config_private.db_password,db=config_private.db_name)
        self.cursor=self.connection.cursor()
        self.log.info("Successfully initialized")

    def call(self):
        self.log.info("Beginning a new run")
        # Getting info from OWM
        try:
            self.log.info("Getting weather data from OpenWeatherMap")
            forecast=self.owm.three_hours_forecast(config_private.openweather_cityname).get_forecast()
            self.log.debug(str(forecast))
        except Exception as exc:
            exc_type, exc_obj, exc_tb = sys.exc_info()
            self.log.error("Unable to get weather data from OpenWeatherMap - TBINFO:"+str(traceback.extract_tb(exc_tb)))
            return
        # Parsing infro got from OWM
        self.log.info("Parsing weather data from OpenWeatherMap")
        weathers=[]
        for f in forecast:
            time_from=datetime.utcfromtimestamp(f.get_reference_time())
            time_to=time_from+timedelta(hours=3)
            temperature=0
            try: temperature=f.get_temperature(unit='celsius')["temp"]
            except Exception as exc: pass
            pressure=0
            try: pressure=f.get_pressure()["press"]
            except Exception as exc: pass
            humidity=0
            try: humidity=f.get_humidity()
            except Exception as exc: pass
            cloudiness=0
            try: cloudiness=f.get_clouds()
            except Exception as exc: pass
            wind_speed=0
            try: wind_speed=f.get_wind()["speed"]
            except Exception as exc: pass
            wind_dir=0
            try: wind_dir=f.get_wind()["deg"]
            except Exception as exc: pass
            snow_last3h=0
            try: snow_last3h=f.get_snow()["3h"]
            except KeyError: pass
            weather_cond_id=f.get_weather_code()
            weather_cond_desc=f.get_detailed_status()
            w=Weather(time_from,time_to,temperature,pressure,humidity,weather_cond_id,weather_cond_desc,cloudiness,wind_speed,wind_dir,snow_last3h)
            self.log.debug("Got from OpenWeatherMap: "+str(w))
            weathers.append(w)
        # Inserting info into database
        self.log.info("Writing weather data from OpenWeatherMap into database")
        for w in weathers:
            self.cursor.execute("start transaction")
            self.log.debug("Transaction started")
            try:
                query="delete from WEATHER_DATA_FORECAST where timestamp_from like '"+str(w.time_from)+"'"
                self.log.debug(query)
                try:
                    self.cursor.execute(query)
                except pymysql.err.IntegrityError as e:
                    self.log.debug("Skipping update for this row: already referenced")
                    self.cursor.execute("rollback")
                    self.log.debug("Rollback done")
                    continue
                self.log.debug("Delete query successfully executed")
                query="insert into WEATHER_DATA_FORECAST (timestamp_from,timestamp_to,temperature,pressure,humidity,cloudiness,wind_speed,wind_dir,snow_last3h,weather_cond_id) values ("
                query+="'"+str(w.time_from)+"',"
                query+="'"+str(w.time_to)+"',"
                query+=str(w.temperature)+","
                query+=str(w.pressure)+","
                query+=str(w.humidity)+","
                query+=str(w.cloudiness)+","
                query+=str(w.wind_speed)+","
                query+=str(w.wind_dir)+","
                query+=str(w.snow_last3h)+","
                query+=str(w.weather_cond_id)+")"
                self.log.debug(query)
                self.cursor.execute(query)
                self.log.debug("Insert query successfully executed")
                self.cursor.execute("commit")
                self.log.debug("Commit done")
            except Exception as e:
                exc_type, exc_obj, exc_tb = sys.exc_info()
                self.log.error("Unable to write weather data to database: "+str(e)+" - TBINFO:"+str(traceback.extract_tb(exc_tb)))
                self.cursor.execute("rollback")
                self.log.debug("Rollback done")
        self.log.info("Done this run")

    def cleanup(self):
        self.log.info("Cleaning up")
        self.cursor.close()
        self.connection.close()
        self.log.info("Successfully cleaned up")
示例#48
0
from gpiozero import LED
from pyowm import OWM
import pyowm

sunny = LED(17)
rain = LED(18)
cold = LED(19)
hot = LED(20)

API_KEY = '695b1925a51da2f8e4123e099501cdf6'
owm = OWM(API_key=API_KEY, language='de')

mainzId = 2874225

#mainzWeather = owm.weather_at_id(mainzId)
mainzFc = owm.three_hours_forecast_at_id(mainzId)
mainzF = mainzFc.get_forecast()
weatherList = mainzF.get_weathers()
threeHours = 3*60*60
newWeatherList = []
time = mainzFc.when_starts()
interval = mainzF.get_interval()
reception_time = mainzF.get_reception_time(timeformat='unix')
location = mainzF.get_location()


for i in range(0,2):
	newWeatherList.append(mainzFc.get_weather_at(time+threeHours*i))

MainzF = pyowm.webapi25.forecast.Forecast(interval,reception_time,location,newWeatherList)
MainzFc = pyowm.webapi25.forecaster.Forecaster(MainzF)
示例#49
0
import argparse
import datetime
import json

with open('keys.json', 'r') as f:
    key_dict = json.load(f)
api_key = key_dict['api_key']

# Parse arguments
parser = argparse.ArgumentParser(description='Show the current weather.')
parser.add_argument("-l", "--location", help="The location where you want to know the weather", default="Tampere, FI")
args = parser.parse_args()
location = args.location

# Collect info
owm = OWM(API_key=api_key, language='en')
observation = owm.weather_at_place(location)
weather = observation.get_weather()
temp = weather.get_temperature(unit='celsius')['temp']
status = weather.get_status()
forecaster = owm.three_hours_forecast(location)
forecast = forecaster.get_forecast()
location = observation.get_location().get_name()

print('')
print('Current weather in %s:' % (location))
print('Temperature: %.1f degrees celsius' % (temp))
print('Sky: %s' % (status))
print('')
print('Forecast:')
for i in range(4):
from pyowm import OWM
import unicodedata

API_key = '<enter api key here>'

location_str = 'Hallbergmoos, DE'



owm = OWM(API_key, language='de')

if owm.is_API_online():

    obs = owm.weather_at_place(location_str)
    w = obs.get_weather()

    print('reference_time())                 ', w.get_reference_time())                             # get time of observation in GMT UNIXtime
    print('reference_time(timeformat="iso")) ', w.get_reference_time(timeformat="iso"))             # ...or in ISO8601
    print('clouds())                         ', w.get_clouds())                                     # Get cloud coverage
    print('rain())                           ', w.get_rain())                                       # Get rain volume
    print('snow())                           ', w.get_snow())                                       # Get snow volume
    print('wind())                           ', w.get_wind())                                       # Get wind degree and speed
    print('humidity())                       ', w.get_humidity())                                   # Get humidity percentage
    print('pressure())                       ', w.get_pressure())                                   # Get atmospheric pressure
    print('temperature())                    ', w.get_temperature())                                # Get temperature in Kelvin
    print('temperature(unit="celsius"))      ', w.get_temperature(unit="celsius"))                  # ... or in Celsius degs
    print('temperature("fahrenheit"))        ', w.get_temperature("fahrenheit"))                    # ... or in Fahrenheit degs
    print('status())                         ', w.get_status())                                     # Get weather short status
    print('detailed_status())                ', w.get_detailed_status())                            # Get detailed weather status
    print('weather_code())                   ', w.get_weather_code())                               # Get OWM weather condition code
    print('weather_icon_name())              ', w.get_weather_icon_name())                          # Get weather-related icon name
示例#51
0
for i in range(NoInvert):
# Read data from inverter
  inverter = ModbusClient(method='rtu', port='/dev/ttyUSB'+str(i), baudrate=9600, stopbits=1, parity='N', bytesize=8, timeout=1)
  inverter.connect()
  rr = inverter.read_input_registers(1,27)
  inverter.close()
  value=rr.registers[2]
  pv_volts=pv_volts+(float(value)/10)
  value=rr.registers[11]
  pv_power=pv_power+(float(value)/10)
  value=rr.registers[26]
  Wh_today=Wh_today+(float(value)*100)

if OWMKey<>'':
  owm = OWM(OWMKey)
  if owm.API_online:
    obs = owm.weather_at_coords(OWMLat, OWMLon)
    w = obs.get_weather()
    w_stat = w.get_detailed_status()
    temp = w.get_temperature(unit='celsius')
    current_temp = temp['temp']
    cloud_pct = w.get_clouds()
    com_str= ('%s with a cloud coverage of %s percent' %(w_stat,cloud_pct))

cmd=('curl -d "d=%s" -d "t=%s" -d "v1=%s" -d "v2=%s" -d "v5=%s" -d "v6=%s" -d "c1=0" -H \
"X-Pvoutput-Apikey: %s" -H \
"X-Pvoutput-SystemId: %s" \
http://pvoutput.org/service/r2/addstatus.jsp'\
%(t_date, t_time, Wh_today, pv_power, current_temp, pv_volts,\
APIKEY, SYSTEMID))
# April 2015        Alistair Bill
# February 2016     Marek Hobler 

import os 
import datetime
import codecs
import argparse

from pyowm import OWM

parser = argparse.ArgumentParser()
parser.add_argument('--owmkey', help='API key to http://openweathermap.org/', required=True)
parser.add_argument('--city', help='City', default='Wroclaw, PL')
args = parser.parse_args()

owm = OWM(language='en', API_key=args.owmkey, version='2.5')

icons = []
icons_parse = []
highs = []
lows = []
dates = []

forecast = owm.daily_forecast(args.city, limit=4).get_forecast()
for weather in forecast:
# Parse icons
    icons.append(weather.get_weather_code())
# Parse temperature highs
    highs.append(round(weather.get_temperature(unit='celsius')['max'], 1))
# Parse temperature lows
    lows.append(round(weather.get_temperature(unit='celsius')['min'], 1))
示例#53
0
文件: podaga.py 项目: Regaerd/Podaga
class Podaga(object):
    T, B, C, L, R = range(5)
    kMARGIN = 1
    kUPDATE_INTERVAL = 15 # minutes
    kGEO_URL = 'http://freegeoip.net/json/'
    kDEFAULT_TEMP_UNIT = 'fahrenheit'
    kTIMESTAMP_FORMAT = '%I:%M:%S %p'
    kMAX_TRIES = 5

    def __init__(self, stdscr, args=None):
        self.stdscr = stdscr
        self.owm = OWM(API_key=args.api_key)

        self.find_location()
        self.location_name = "{}, {}".format(self.location['city'], self.location['region_name'])
        # self.loc = self.owm.weather_at_coords(self.location['latitude'], self.location['longitude'])
        self.temp_unit = args.temp_unit
        self.temp_symbol = self.temp_unit[0].upper()
        self.forecast = None
        self.spinner = Spinner(Spin1)
        self.bar_animation = 1
        self.last_update = None
        self.verbose = False
        self.error = ""

        try: # needed for terminals that don't support all color options
            for i in range(256):
                curses.init_pair(i+1, i, -1)
                self.color_range = i
        except:
            pass

        self.color_pri = curses.color_pair(2) | curses.A_BOLD
        self.color_sec = curses.color_pair(4) | curses.A_BOLD
        self.color_ext = curses.color_pair(5) | curses.A_BOLD

        self.draw_height = 2
        self.draw_width = 0 # generated by view_resized
        self.tries = 0
        self.view_resized()

    def update(self):
        time = int(strftime("%M"))
        if not self.last_update or self.last_update != time and time % self.kUPDATE_INTERVAL == 0:
            try: # Open Weather Map sometimes fails
                self.loc = self.owm.weather_at_place(self.location_name)
                self.forecast = self.loc.get_weather()
                self.last_update = time
                self.last_update_timestamp = "Updated: {}".format(strftime(self.kTIMESTAMP_FORMAT))
            except Exception, e:
                self.error = e.message
                self.tries += 1
                if self.tries >= self.kMAX_TRIES:
                    self.tries = 0
                    self.last_update = time
                    self.error = 'Exceeded max tries. Waiting till next update window. {}'.format(self.error)

        for window in self.windows: window.box()

        animation = self.spinner.next()
        self.draw(self.win_l, self.T, self.R, animation, self.color_ext)
        self.draw(self.win_r, self.T, self.L, animation, self.color_ext)

        if (self.forecast): # we won't have a forecast if owm fails on the initial call
            self.draw(self.win_l, self.T, self.L, self.location_name, self.color_pri)
            self.draw(self.win_l, self.B, self.L, self.forecast.get_detailed_status().capitalize(), self.color_sec)

            self.draw(self.win_c, self.T, self.C, "{} °{}".format(self.forecast.get_temperature(self.temp_unit)["temp"], self.temp_symbol), self.color_pri)
            self.draw(self.win_c, self.B, self.L, "{} m/s".format(self.forecast.get_wind()["speed"]), self.color_sec)
            self.draw(self.win_c, self.B, self.R, "{} %".format(self.forecast.get_humidity()), self.color_sec)

            self.draw(self.win_r, self.T, self.R, self.location['ip'], self.color_pri)
            self.draw(self.win_r, self.B, self.R, self.last_update_timestamp, self.color_sec)
        else:
            self.draw_error(self.stdscr, self.error)

        for window in self.windows: window.refresh()

        if self.verbose:
            self.stdscr.clrtoeol()
            self.stdscr.addstr(0, 0, json.dumps(self.location))

        self.stdscr.refresh()
示例#54
0
文件: update.py 项目: combs/mirf-base
mydir = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.dirname(mydir))
sys.path.append(os.path.dirname(mydir)+ "/common")

from MirfBase import MirfBase

mirf = MirfBase()
mirf.try_cache(60*15)

degrees = str(chr(223))
apikey=None

with open(mydir + "/.api-key-openweathermap", "rb") as apifile:
    apikey = apifile.readline().strip()

owm = OWM(apikey)

placename='20017,US'

wap = owm.weather_at_place(placename)
w = wap.get_weather()
fc = owm.daily_forecast(placename, limit=1)


outputConditions = "C"
outputNow = "N"
outputLater = "L"
output1 = "0                "
output2 = "1                "

status = w.get_status()
示例#55
0
    def onTextMessage(self, messageProtocolEntity):

        nombre = messageProtocolEntity.getNotify()
        mensaje = messageProtocolEntity.getBody()
        para = messageProtocolEntity.getFrom()
        
        print 'Esta hablando: ' + nombre
        
        archivo = open('RegistroDeUsuarios.txt', 'a')
        archivo.write(time.strftime("%d/%m/%y"))
        archivo.write("|")
        archivo.write(time.strftime("%H:%M:%S"))
        archivo.write("|")
        archivo.write(para)
        archivo.write("|")
        archivo.write(nombre)
        archivo.write("\n")
        archivo.close() # Fin de registro de usuarios
        if mensaje == 'Hola':
            msg1 = "Hola " + nombre + " como estas ?"
            self.toLower(TextMessageProtocolEntity(msg1, to=para))
        elif 'Clima' in mensaje:
                ParaClima = mensaje.split(' ')
                owm_es = OWM(language='es')
                Pais = ',Arg'
                API_key = '12345678'
                owm = OWM(API_key)
                apikey = owm.get_API_key()
                owm.set_API_key(API_key)
                observation = owm.weather_at_place(ParaClima[1] + Pais)
                w = observation.get_weather()
                presion = str(w.get_pressure())
                presionseparada = presion.split(':')
                presA = presionseparada[1]
                PresF = presA.split(',')
                time.sleep(1)
                temperatura = str(w.get_temperature('celsius'))
                temperaturaSeparada = temperatura.split(':')
                TempA = temperaturaSeparada[3]
                TempF = TempA.split(',')
                humedad = w.get_humidity()
                self.toLower(TextMessageProtocolEntity('Presion: ' + PresF[0] + ' hPa\n''Temperatura: ' + TempF[0] + '[C]\n'+ 'Humedad: ' + str(humedad) + ' %' , to=para))
                time.sleep(1)
                os.system("twitter set Me ha consultado " + nombre + "...")
                time.sleep(1)
        elif 'Wa ' in mensaje:
                id= 'XXXXXXXXXX-XXXXX' #Aca va la id que tenes de wolfram, si queres ponersela te tenes que registrar
                file = open('HistorialWA.txt', 'a')
                client = wolframalpha.Client(id)
                self.toLower(TextMessageProtocolEntity("Mathematica está calculando...", to=para))
            try:
                ParaWolfram = mensaje.split(" ")
                res = client.query(str(ParaWolfram[1]+' '+(ParaWolfram[2])))
                #Esto viene a ser un registro para saber quien fue
                # el que calculó,solo por seguridad
                file.write(str(ParaWolfram[1]+' '+(ParaWolfram[2])))
                file.write("|")
                file.write(time.strftime("%d/%m/%y"))
                file.write("|")
                file.write(time.strftime("%H:%M:%S"))
                file.write("|")
                file.write(para)
                file.write("|")
                file.write(nombre)
                file.write("\n")
                if len(res.pods) > 0:
                    texts = ""
                    pod = res.pods[1]
                if pod.text:
                    texts = pod.text
                    texts = texts.encode('ascii', 'ignore')
                    self.toLower(TextMessageProtocolEntity("Resultado:", to=para))
                    self.toLower(TextMessageProtocolEntity(texts, to=para))
                else:
                    texts = "No Tengo respuesta: Atte Don Wolfram."
                    self.toLower(TextMessageProtocolEntity(texts, to=para))
            except NameError:
                # Si me da el error de Pot
                self.toLower(TextMessageProtocolEntity("Comando Wa inválido\nError de Nombres", to=para))
            except IndexError:
                # Si Se Va de rango..(en las derivadas /integrales pasa..)
                self.toLower(TextMessageProtocolEntity("Comando Wa inválido\nindice fuera de rango", to=para))
        elif mensaje == 'Gracias':
                msg10 = "Estoy siendo programado, teneme paciencia"
                time.sleep(1)
                msg11 = "Para mas informacion, escribe Menu"
                time.sleep(2)
                self.toLower(TextMessageProtocolEntity(msg10, to=para))
                time.sleep(1)
                self.toLower(TextMessageProtocolEntity(msg11, to=para))
示例#56
0
class WeatherPoller(object):

    API_key = '9ef86a5c847ad6a5c67d09dd9b72e9a6'
    API_fetch_interval = timedelta(days=1)
    map_city_id = {'kitchener': 5992996}
    temperature_change_threshold = 5.0

    def __init__(self, city='kitchener'):
        if city in WeatherPoller.map_city_id:
            self.city_id = WeatherPoller.map_city_id[city]
        else:
            logging.error(' '.join([self.__class__.__name__, ": city:", city,
                                    "not found in map_city_id dict."]))
            raise Exception("city:", city, " not found in map_city_id dict.")

        self.owm = None
        self.last_api_fetch_time = None

    def poll_data(self):
        if self.owm is None or self.last_api_fetch_time is None \
                or self.forecast is None or \
                (datetime.utcnow() - self.last_api_fetch_time >
                 WeatherPoller.API_fetch_interval):
            self.owm = OWM(WeatherPoller.API_key)
            self.forecast = self.owm.daily_forecast_at_id(self.city_id)
            self.last_api_fetch_time = datetime.utcnow()
            logging.info(' '.join(
                [self.__class__.__name__, ": poll_data() fetched new data at:",
                 self.last_api_fetch_time.isoformat()]))
        else:
            logging.info(' '.join([self.__class__.__name__, (
                ": poll_data() called within fetch "
                "interval threshold, use previous "
                "fetched data at:"), self.last_api_fetch_time.isoformat()]))

    def trigger_notification(self, message):
        print message

    def check_temperature_change(self):
        weather_lst = self.forecast.get_forecast().get_weathers()
        today = datetime.utcnow()
        tomorrow = today + timedelta(days=1)
        today_temp = weather_lst[0].get_temperature(unit='celsius')
        tomorrow_temp = self.forecast.get_weather_at(tomorrow).get_temperature(
            unit='celsius')

        logging.debug(' '.join(
            [self.__class__.__name__, ": check_temperature_change", "\ntoday:",
             str(today_temp), "\ntomorrow", str(tomorrow_temp)]))

        alert_lst = []
        for item in today_temp:
            if abs(today_temp[item] - tomorrow_temp[
                    item]) >= WeatherPoller.temperature_change_threshold:
                alert_lst.append(
                    "Temperature change alert:"
                    "item: {key}, today:{today}, tomorrow:{tomorrow}".format(
                        key=item,
                        today=today_temp[item],
                        tomorrow=tomorrow_temp[item]))
        return alert_lst
示例#57
0
from pyowm import OWM
import serial
import time

ser = serial.Serial(3) #replace with COMPORT -1
ser.baudrate = 9600
ser.close()
ser.open()

API_key = '2417d98e524df449d7930e013b398e5d'
owm = OWM(API_key)
obs = owm.weather_at('Boston,US')
w = obs.get_weather()
temp = w.get_temperature()['temp'] # pulls temperature in kelvin
temp = (9/5)*(temp - 273) + 32 #converts to fahrenheit
wind = w.get_wind()['speed']


while True:
	if temp > 90:
		if wind > 10:
			ser.write(str(5).encode()) 
		else:
			ser.write(str(1).encode())
	elif temp < 90 and temp > 75:
		if wind > 10:
			ser.write(str(5).encode())
		else:
			ser.write(str(2).encode())
	elif temp <= 75 and temp > 60:
		if wind > 10:
示例#58
0
文件: views.py 项目: BibianaC/weather
def get_forecast(location, days):
    owm = OWM(WEATHER_API_KEY)
    daily_forecast = owm.daily_forecast(location, limit=days)
    forecast_data = daily_forecast.get_forecast()
    return forecast(forecast_data)
示例#59
0
class WeatherRealtimeUpdaterThread(LoopingThread):

    def initialize(self):
        self.log=LoggerFactory.get_file_logger(config.log_filename,"WeatherRealtimeUpdaterThread",config.log_level)
        self.log.info("Initializing")
        self.owm=OWM(config_private.openweather_key)
        self.connection=pymysql.connect(host=config_private.db_host,port=config_private.db_port,user=config_private.db_user,passwd=config_private.db_password,db=config_private.db_name)
        self.cursor=self.connection.cursor()
        self.log.info("Successfully initialized")

    def call(self):
        self.log.info("Beginning a new run")
        # Getting info from OWM
        try:
            self.log.info("Getting weather data from OpenWeatherMap")
            obs=self.owm.weather_at_place(config_private.openweather_cityname)
            obswea=obs.get_weather()
            self.log.debug(str(obswea))
            # Parsing info got from OWM
            self.log.info("Parsing weather data from OpenWeatherMap")
            time_from=time_to=datetime.utcnow()
            temperature=0
            try: temperature=obswea.get_temperature(unit='celsius')["temp"]
            except Exception as exc: pass
            pressure=0
            try: pressure=obswea.get_pressure()["press"]
            except Exception as exc: pass
            humidity=0
            try: humidity=obswea.get_humidity()
            except Exception as exc: pass
            cloudiness=0
            try: cloudiness=obswea.get_clouds()
            except Exception as exc: pass
            wind_speed=0
            try: wind_speed=obswea.get_wind()["speed"]
            except Exception as exc: pass
            wind_dir=0
            try: wind_dir=obswea.get_wind()["deg"]
            except Exception as exc: pass
            snow_last3h=0
            try: snow_last3h=obswea.get_snow()["3h"]
            except KeyError: pass
            weather_cond_id=obswea.get_weather_code()
            weather_cond_desc=obswea.get_detailed_status()
            w=Weather(time_from,time_from,temperature,pressure,humidity,weather_cond_id,weather_cond_desc,cloudiness,wind_speed,wind_dir,snow_last3h)
            self.log.debug("Got from OpenWeatherMap: "+str(w))
        except Exception as exc:
            exc_type, exc_obj, exc_tb = sys.exc_info()
            self.log.error("Unable to get weather realtime data from OpenWeatherMap - TBINFO: "+str(traceback.extract_tb(exc_tb)))
            self.log.warning("Trying to use forecast instead of real time data")
            try:
                query="select * from WEATHER_DATA_FORECAST where UTC_TIMESTAMP() between timestamp_from and timestamp_to"
                self.log.debug(query)
                self.cursor.execute(query)
                row=self.cursor.fetchone()
                now=datetime.utcnow()
                time_from,time_to,temperature,pressure,humidity,cloudiness,wind_speed,wind_dir,snow_last3h,weather_cond_id=row
                w=Weather(now,now,temperature,pressure,humidity,weather_cond_id,"__FORECAST__",cloudiness,wind_speed,wind_dir,snow_last3h)
                self.log.debug("Got from forecast: "+str(w))
            except Exception as e:
                exc_type, exc_obj, exc_tb = sys.exc_info()
                self.log.error("Unable to get weather realtime data from OpenWeatherMap and forecast data from database!!!")
                self.log.error(str(e)+" - TBINFO:"+str(traceback.extract_tb(exc_tb)))
                return
        # Inserting info into database
        try:
            self.log.info("Writing weather data into database")
            query="insert into WEATHER_DATA_REALTIME (timestamp,temperature,pressure,humidity,cloudiness,wind_speed,wind_dir,snow_last3h,weather_cond_id) values ("
            query+="'"+str(w.time_from)+"',"
            query+=str(w.temperature)+","
            query+=str(w.pressure)+","
            query+=str(w.humidity)+","
            query+=str(w.cloudiness)+","
            query+=str(w.wind_speed)+","
            query+=str(w.wind_dir)+","
            query+=str(w.snow_last3h)+","
            query+=str(w.weather_cond_id)+")"
            self.log.debug(query)
            self.cursor.execute(query)
            self.log.debug("Insert query successfully executed")
        except Exception as e:
            exc_type, exc_obj, exc_tb = sys.exc_info()
            self.log.error("Unable to write weather data to database: "+str(e)+" - TBINFO:"+str(traceback.extract_tb(exc_tb)))
            self.cursor.execute("rollback")
            self.log.debug("Rollback done")
        self.cursor.execute("commit")
        self.log.debug("Commit done")
        self.log.info("Done this run")

    def cleanup(self):
        self.log.info("Cleaning up")
        self.cursor.close()
        self.connection.close()
        self.log.info("Successfully cleaned up")
示例#60
-1
 def poll_data(self):
     if self.owm is None or self.last_api_fetch_time is None \
             or self.forecast is None or \
             (datetime.utcnow() - self.last_api_fetch_time >
              WeatherPoller.API_fetch_interval):
         self.owm = OWM(WeatherPoller.API_key)
         self.forecast = self.owm.daily_forecast_at_id(self.city_id)
         self.last_api_fetch_time = datetime.utcnow()
         logging.info(' '.join(
             [self.__class__.__name__, ": poll_data() fetched new data at:",
              self.last_api_fetch_time.isoformat()]))
     else:
         logging.info(' '.join([self.__class__.__name__, (
             ": poll_data() called within fetch "
             "interval threshold, use previous "
             "fetched data at:"), self.last_api_fetch_time.isoformat()]))