Ejemplo n.º 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
Ejemplo n.º 2
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
Ejemplo n.º 3
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)
Ejemplo n.º 4
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
Ejemplo n.º 5
0
 def _get_weather_status_and_temperature(cls, city):
     owm = OWM(API_key=WEATHER_API['key'])
     if owm.is_API_online():
         obs = owm.weather_at_place(city)
         weather = obs.get_weather()
         status = weather.get_status()
         temperature = weather.get_temperature(WEATHER_API['unit'])
         return status, temperature
     else:
         return None, None
Ejemplo n.º 6
0
def get_open_weather_map(*, config: Box) -> Optional[Dict]:
    """Fetch and write the Open Weather Map data."""
    try:
        owm_id = config.open_weather_map["id"]
        latitude = float(config.open_weather_map["latitude"])
        longitude = float(config.open_weather_map["longitude"])
    except KeyError:
        log.error(
            "The config file does not contain all Open Weather Map config keys (id, latitude, longitude). Cannot continue."
        )
        sys.exit(1)
    if owm_id.lower() == "none":
        log.debug("Open Weather Map is not configured.")
        return

    open_weather_map = OWM(owm_id)
    if not open_weather_map.is_API_online():
        log.warning("Open Weather Map endpoint is not online-line.")
        return
    start_ts = arrow.utcnow()
    try:
        weather = open_weather_map.weather_at_coords(latitude, longitude)
    except Exception as e:
        log.warning("Could not fetch weather: {}.".format(str(e)))
        return
    else:
        elapsed_time = arrow.utcnow() - start_ts
        log.debug(
            f"Fetching Open Weather Map took {elapsed_time.total_seconds():.3f} s."
        )
    try:
        weather = json.loads(weather.to_JSON())
    except json.JSONDecodeError as e:
        log.warning(f"Could not JSON decode weather data: {e}.")
    except Exception as e:
        log.warning(f"Could not convert weather data {weather} to JSON: {e}.")
        return
    return weather
Ejemplo n.º 7
0
def weather_command(message, handler, args):
    try:
        open_weather_map = OWM(settings["open_weather_key"])
        if  open_weather_map.is_API_online():
            # observation
            query = args[0] + ", " + args[1]
            obs = open_weather_map.weather_at_place(query)
            # weather
            weather = obs.get_weather()
            wind = weather.get_wind()
            temp = weather.get_temperature(unit="celsius")
            #location
            loc = obs.get_location()
            msg = ":partly_sunny: **Weather** :thunder_cloud_rain:\n"
            msg += "**City:** {}\t**Country:** {}\n**Latitude:** {}\t**Longitude:** {}\n**Status:** {}\n**Temperature** :thermometer:\n**Average:** {}ºC\t**Max:** {}ºC\t**Min:** {}ºC\n**Wind:** {}m/s"
            msg = msg.format(loc.get_name(), args[1].upper(), loc.get_lat(), loc.get_lon(), weather.get_detailed_status(), temp["temp"], temp["temp_max"], temp["temp_min"], wind["speed"])
            return msg
        else:
            return ":no_entry: **ERROR** :no_entry: : OpeanWeatherMap API is offline!"
    except Exception as e:
        template = "An exception of type {0} occurred. Arguments:\n{1!r}"
        message = template.format(type(e).__name__, e.args)
        print(message)
Ejemplo n.º 8
0
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
Ejemplo n.º 9
0
                            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.is_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))
Ejemplo n.º 10
0
    time.sleep(3.5)

    mylcd.lcd_clear()
    mylcd.lcd_display_string("Teraz: " + str(itime_current)+ "  ",1 )
    mylcd.lcd_display_string("Wilgotnosc:" + str(ihumidity_current)+ "%",2 )
    time.sleep(3.5)
    
    mylcd.lcd_clear()
    mylcd.lcd_display_string("Przypomnienie: ",1 )
    mylcd.lcd_display_string("Wyniesc smieci",2 ) #)
    time.sleep(3.5)
    
while(True):
    try:
        while (True):
            if(owm.is_API_online() == True):
                    current_datetime = datetime.datetime.now()
                    #print("cur_dattime:" + str(current_datetime))
                    forecast_time = current_datetime + datetime.timedelta(hours=6)
                    current_time = current_datetime.time()
                    #print("cur" + str(current_time))
                    curr_object = cu.get_weather()
                    forecast_object = fc.get_weather_at(forecast_time)

                    time_forecast = forecast_object.get_reference_time(timeformat='date')
                    #Zmienne zawierające dane o temperaturze
                    temp_forecast = forecast_object.get_temperature(unit='celsius')
                    temp_curr = curr_object.get_temperature(unit='celsius')
                    #Zmienne zawierające dane o pogodzie
                    status_forecast = forecast_object.get_detailed_status()
                    status_curr = curr_object.get_detailed_status()