def yrno(location): locs = { 'Chałupy': 'Poland/Pomerania/Chałupy/', 'Jastarnia': 'Poland/Pomerania/Jastarnia/', 'Jurata': 'Poland/Pomerania/Jurata/', 'Kadyny': 'Poland/Warmia-Masuria/Kadyny/', 'Kuźnica': 'Poland/Pomerania/Kuźnica/', 'Rewa': 'Poland/Pomerania/Rewa/' } weather = Yr(location_name=locs[location]) forecasts = [] for fcast in weather.forecast(): date = fcast['@from'].replace('T', ' ')[0:-3] temp = int(fcast['temperature']['@value']) wind_dir = fcast['windDirection']['@code'] wind_speed_mps = int(float(fcast['windSpeed']['@mps'])) wind_speed_kts = int(wind_speed_mps * KTS_TO_MPS) prec = float(fcast['precipitation']['@value']) pretty_date = re.search(r'\d{4}-(\d{2})-(\d{2}) (\d{2})', date) date = (pretty_date.group(2) + '.' + pretty_date.group(1)) hour = pretty_date.group(3) + ':00' forecast = Forcast(date=date, hour=hour, temp=temp, wind_dir=wind_dir, wind_speed_kts=wind_speed_kts, wind_speed_mps=wind_speed_mps, prec=prec) forecasts.append(forecast) print(forecast) return forecasts
def refresh_cache(self): weather = Yr(location_name=self.location, forecast_link="forecast_hour_by_hour") weather_forecast = weather.forecast(as_json=False) self.cached_forecasts = [ self.convert_forecast(forecast) for forecast in weather_forecast ] self.last_refresh = datetime.datetime.now()
def daily_summary(self) -> pd.DataFrame: """Creates a 7-day forecast summary""" data = Yr(location_name=self.location) df = pd.DataFrame([self._process_data(x) for x in data.forecast()]) # We'll need to group by day and have high/low calculated for each metric keep_cols = ['from', 'precipIntensity', 'windSpeed', 'temperature', 'pressure'] df = df[keep_cols].groupby(pd.Grouper(key='from', freq='D')).agg( {x: ['min', 'max'] for x in keep_cols[1:]} ) # Flatten the columns for the dataframe, but keep everything preserved from each level df.columns = ['_'.join(col).strip() for col in df.columns.values] return df
def run(self): arguments = dict() if self.__params.location_xyz is not None: arguments['location_xyz'] = self.__params.location_name elif self.__params.location_name is not None: arguments['location_name'] = self.__params.location_name else: raise Exception('Location must be defined') weather = Yr(**arguments) search_day = self.get_searched_days() for forecast in weather.forecast(): if datetime.fromisoformat(forecast['@from']).date() in search_day: # todo: report expected weather print(forecast)
def update_forecast(location): evo_forecast = { 'min': { 'timestamp': 0, 'temp': 100, 'symbol': '1' }, 'max': { 'timestamp': 0, 'temp': -100, 'symbol': '1' } } now = int(time.time()) weather = Yr(location_name=location, forecast_link='forecast_hour_by_hour') for forecast in weather.forecast(as_json=False): from_time = forecast['@from'] timestamp = int(date_parser.parse(from_time).timestamp()) if timestamp < now or timestamp > now + 12 * 3600: continue symbol = forecast['symbol']['@var'] temp = int(forecast['temperature']['@value']) #print(timestamp, from_time, symbol, temp) if temp <= evo_forecast['min']['temp']: evo_forecast['min']['temp'] = temp evo_forecast['min']['timestamp'] = timestamp evo_forecast['min']['symbol'] = symbol if temp > evo_forecast['max']['temp']: evo_forecast['max']['temp'] = temp evo_forecast['max']['timestamp'] = timestamp evo_forecast['max']['symbol'] = symbol requests.post('http://localhost:3333/evo/forecast', json=evo_forecast)
def yr(what, county, municipality, name): """ Downloads data from yr.no @todo: Should fix units @todo: Should be based on locations and/or clubs default location in clubs '/yr/wind/375-F' """ yrpath = ("Norge/%s/%s/%s" % (county, municipality, name)) weather = Yr(location_name=yrpath) if what == 'now': return weather.now(as_json=True) elif what == 'forecast': return jsonify(**weather.dictionary['weatherdata']['forecast']) elif what == 'wind': wind_speed = dict() wind_speed['wind_forecast'] = [{'from': forecast['@from'], 'to': forecast['@to'], '@unit': 'knots', 'speed': round(float(forecast['windSpeed']['@mps']) * 1.943844, 2)} for forecast in weather.forecast()] return jsonify(**wind_speed)
def yr(what, county, municipality, name): """ Downloads data from yr.no @todo: Should fix units @todo: Should be based on locations and/or clubs default location in clubs '/yr/wind/375-F' """ yrpath = ("Norge/%s/%s/%s" % (county, municipality, name)) weather = Yr(location_name=yrpath) if what == 'now': return weather.now(as_json=True) elif what == 'forecast': return jsonify(**weather.dictionary['weatherdata']['forecast']) elif what == 'wind': wind_speed = dict() wind_speed['wind_forecast'] = [{'from': forecast['@from'], 'to': forecast['@to'], 'unit': 'knots', 'speed': round(float(forecast['windSpeed']['@mps']) * 1.943844, 2)} for forecast in weather.forecast()] return jsonify(**wind_speed)
#!/usr/bin/env python3 from yr.libyr import Yr weather = Yr(location_name='Norway/Rogaland/Stavanger/Stavanger', forecast_link='forecast_hour_by_hour') for forecast in weather.forecast(): print(forecast)
def main(): while True: if args.tanaman: def on_publish_plant(client, userdata, mid): print("mid: " + str(mid)) client = mqtt.Client() client.on_publish = on_publish_plant client.username_pw_set("username", "password") client.connect("broker.hivemq.com", 1883, 60) client.loop_start() lokasi = input("Masukan Lokasi yang ingin di prediksi cuacanya: ") # perulangan untuk mengirimkan data (publish) ke mqtt broker setiap detik while True: weather = Yr(location_name=lokasi, forecast_link='forecast_hour_by_hour') currentWeather = weather.now() minTemp = int(currentWeather['temperature']['@value']) maxTemp = int(currentWeather['temperature']['@value']) maxRain = float(currentWeather['precipitation']['@value']) tempMin = "Minimum Temperatur : " + str(minTemp) tempMax = "Maksimum Temperatur : " + str(maxTemp) rainMax = "Curah Hujan : " + str(maxRain) if maxRain < 0.5: condition = "Siram Tanaman" if maxRain > 0.5: condition = "Jangan Siram Tanaman" client.publish("/temperatur_minimum", tempMin, qos=1) time.sleep(1) client.publish("/temperatur_maksimum", tempMax, qos=1) time.sleep(1) client.publish("/curah_hujan", rainMax, qos=1) time.sleep(1) client.publish("/kondisi_alat_siram", condition, qos=1) time.sleep(2) if args.lampu: def on_publish_light(client, userdata, mid): print("mid: " + str(mid)) client = mqtt.Client() client.on_publish = on_publish_light client.username_pw_set("username", "password") client.connect("broker.hivemq.com", 1883, 60) client.loop_start() lokasi = input("Masukan Lokasi yang ingin di prediksi cuacanya: ") # perulangan untuk mengirimkan data (publish) ke mqtt broker setiap detik while True: weather = Yr(location_name=lokasi, forecast_link='forecast_hour_by_hour') currentWeather = weather.now() sunRise = extractTime(weather.dictionary['weatherdata']['sun'] ['@rise']).strftime("%H:%M") sunSet = extractTime(weather.dictionary['weatherdata']['sun'] ['@set']).strftime("%H:%M") today = datetime.now() timeToday = today.strftime("%H:%M") for forecast in weather.forecast(): condition = forecast['symbol']['@name'] Risesun = "Matahari Terbit : " + str(sunRise) Setsun = "Matahari Terbenam : " + str(sunSet) timenow = "Waktu Sekarang : " + str(timeToday) conditionNow = "Kondisi Cuaca : " + str(condition) if Setsun > timeToday > sunRise and conditionNow != 'Cloudy' or conditionNow != 'Rain' or conditionNow != 'Heavy rain showers': condition = "Lampu Dimatikan" if Setsun < timeToday < sunRise and conditionNow != 'Cloudy' or conditionNow != 'Rain' or conditionNow != 'Heavy rain showers': condition = "Lampu Dihidupkan" if Setsun > timeToday > sunRise and conditionNow == 'Cloudy' or conditionNow == 'Rain' or conditionNow == 'Heavy rain showers': condition = "Lampu Dimatikan" if Setsun < timeToday < sunRise and conditionNow == 'Cloudy' or conditionNow == 'Rain' or conditionNow == 'Heavy rain showers': condition = "Lampu Dihidupkan" client.publish("/matahari_terbit", Risesun, qos=1) time.sleep(1) client.publish("/matahari_terbenam", Setsun, qos=1) time.sleep(1) client.publish("/waktu_sekarang", timenow, qos=1) time.sleep(1) client.publish("/kondisi_sekarang", conditionNow, qos=1) time.sleep(1) client.publish("/kondisi_alat_lampu", condition, qos=1) time.sleep(2) if args.pendingin: def on_publish_cooler(client, userdata, mid): print("mid: " + str(mid)) client = mqtt.Client() client.on_publish = on_publish_cooler client.username_pw_set("username", "password") client.connect("broker.hivemq.com", 1883, 60) client.loop_start() lokasi = input("Masukan Lokasi yang ingin di prediksi cuacanya: ") # perulangan untuk mengirimkan data (publish) ke mqtt broker setiap detik while True: url = "http://api.openweathermap.org/data/2.5/weather?q=%s&appid=%s" request = requests.get( url % (lokasi, '057928f69d86a90014a99e9b80269621')) response = json.loads(request.text) temp = round(response['main']['temp'] - 273) temperatur = "Suhu : " + str(temp) if temp >= 30: condition = "Pendingin Dihidupkan" if 30 >= temp >= 21: condition = "Pendingin Dihidupkan" if temp <= 21: condition = "Pendingin Dimatikan" client.publish("/temperatur", temperatur, qos=1) time.sleep(1) client.publish("/kondisi_alat_pendingin", condition, qos=1) time.sleep(2)
log=sys.argv[2] requestType=int(sys.argv[3]) asJSON=bool("foo") if sys.argv[4]=="F": asJSON=bool("") weather = "" #Get the weather forecast for the specified location if requestType==1: weather=Yr(location_name='Norway/Rogaland/Stavanger/Stavanger') #Get the hourly weather forecast for the specified location elif requestType==2: weather=Yr(location_name='Norway/Rogaland/Stavanger/Stavanger', forecast_link='forecast_hour_by_hour') #Get the current forecast for the specified location else: weather=Yr(location_name='Norway/Rogaland/Stavanger/Stavanger') weatherResponse="" if requestType!=0: if(asJSON): for forecast in weather.forecast(as_json=asJSON): weatherResponse+=forecast else: weatherResponse=weather else: weatherResponse=weather.now(as_json=asJSON) print(weatherResponse)
#!/usr/bin/env python3 from yr.libyr import Yr weather = Yr(location_name='Norge/Telemark/Skien/Skien') wind_speed = dict() wind_speed['data'] = [{ 'from': forecast['@from'], 'to': forecast['@to'], 'speed': float(forecast['windSpeed']['@mps']) } for forecast in weather.forecast()] wind_speed['credit'] = weather.credit print(wind_speed)
class YrForecastToHmi: """ Using json file from yr.no to find forecast for 8 days. https://github.com/wckd/python-yr """ def __init__(self): self.periode_list = [] self.from_list = [] self.to_list = [] self.symbol_list = [] self.symbol_number_list = [] self.temp_list = [] self.rain_list = [] self.weekday_list = [] self.date_list = [] self.symbol_equal_sun = ["Clear sky", "Fair"] # 0 self.symbol_equal_partly_cloudy = ["Partly cloudy"] # 1 self.symbol_equal_cloudy = ["Fog", "Cloudy"] # 2 self.symbol_equal_rain = [ "Light rain", "Light rain showers", # NEW "Light sleet", "Light sleet showers", "Light rain showers and thunder", "Light sleet showers and thunder", "Light rain and thunder", "Light sleet and thunder", "Rain", "Rain showers", "Sleet", "Sleet showers", "Rain showers and thunder", "Sleet showers and thunder", "Rain and thunder", "Sleet and thunder", ] # 3 self.symbol_equal_storm = [ "Heavy rain showers", "Heavy rain", "Heavy sleet", "Heavy sleet showers", "Heavy rain showers and thunder", "Heavy sleet showers and thunder", "Heavy rain and thunder", "Heavy sleet and thunder", ] # 4 self.symbol_equal_snow = [ "Light snow", "Snow", "Heavy snow", "Light snow showers", "Snow showers", "Heavy snow showers", "Light snow showers and thunder", "Snow showers and thunder", "Heavy snow showers and thunder", "Light snow and thunder", "Snow and thunder", "Heavy snow and thunder", ] # 5 self.weather_symbol_list = [ self.symbol_equal_sun, # 0 self.symbol_equal_partly_cloudy, # 1 self.symbol_equal_cloudy, # 2 self.symbol_equal_rain, # 3 self.symbol_equal_storm, # 4 self.symbol_equal_snow, # 5 ] self.flag = False def importForcastLongFromYrInJson(self, place_string): """Import 8 days forcast from Yr.no in json file. Parameters: place_string (string): The place to get the forecast from. Format: "Land/Fylke/Kommune/Stedsnavn/" Example: "Norge/Trøndelag/Trondheim/Trondheim/" Returns: genarator:forecast """ self.json_yr_weather = Yr(location_name=place_string) forecast = self.json_yr_weather.forecast(as_json=True) return forecast def formatDataFromYrToJson(self, forecast_from_yr): """Find the usefull information in the json file and add the information to the right list. Parameters: forecast_from_yr (generator): Use for loop to loop through the generator. Returns: formated_data_list (list): List of lists with formated data """ for forecast in forecast_from_yr: forecast = json.loads(forecast) periode = int(forecast["@period"]) from_time = forecast["@from"] to_time = forecast["@to"] symbol = forecast["symbol"]["@name"] temp = forecast["temperature"]["@value"] rain = forecast["precipitation"]["@value"] dateStr, weekday = self.jsonDateToWeekday(from_time) symbol_number = self.symbolStringToInt(symbol) if periode == 0 and self.flag == False: # Find the first new period to set as new day. self.flag = True if self.flag == True and periode == 2: # Using only period 2 for each day. 12:00-18:00. self.from_list.append(from_time) self.to_list.append(to_time) self.symbol_list.append(symbol) self.symbol_number_list.append(symbol_number) self.temp_list.append(temp) self.rain_list.append(rain) self.weekday_list.append(weekday) self.date_list.append(dateStr) formated_data_list = [ self.from_list, self.to_list, self.symbol_list, self.symbol_number_list, self.temp_list, self.rain_list, self.weekday_list, self.date_list, ] return formated_data_list def jsonDateToWeekday(self, datetimestamp): """Change a date to a weekday in number. Mon:0, Tue:1, Wed:2, Thu:3, Fri:4, Sat:5, Sun:6 Parameters: datetimestamp (str): Format_YYYY-MM-DDTHH:MM:SS Returns: weekday (int): """ dateStr = datetimestamp.split("T")[0] # Split date from "dateTime" year, month, day = (int(x) for x in dateStr.split("-") ) # Convert date to right format weekday = datetime.date(year, month, day).weekday() # Find weekday return dateStr, weekday def symbolStringToInt(self, symbol_string): """Change a symbol to a symbol number. Number given from list in init. Parameters: symbol_string (str): Returns: symbol_number (int): """ symbol_number = None for idx, weather_type in enumerate( self.weather_symbol_list ): # Search list in weather_symbol_list to find weather type if symbol_string in weather_type: symbol_number = ( idx # If found. Symbol number is index of the list in weather_symbol_list ) if symbol_number == None: symbol_number = "Not found" # If not found. Symbol number is "Not found". TODO: Endre til 3 i tilfellet værtypen ikke finnes. return symbol_number def mqttSend(self, formated_data): """Find the usefull information from list to send with MQTT Parameters: formated_data (list): Returns: MQTT_send (dict): """ symbol_number_list = formated_data[3] temp_list = formated_data[4] rain_list = formated_data[5] weekday_list = formated_data[6] MQTT_send = { "day1weekday": weekday_list[0], "day1symbol": symbol_number_list[0], "day1temp": temp_list[0], "day1rain": rain_list[0], "day2weekday": weekday_list[1], "day2symbol": symbol_number_list[1], "day2temp": temp_list[1], "day2rain": rain_list[1], "day3weekday": weekday_list[2], "day3symbol": symbol_number_list[2], "day3temp": temp_list[2], "day3rain": rain_list[2], } print(MQTT_send) return MQTT_send def getForecast(self): """ Main for forcast. Returns: MQTT_send (dict): """ imported_data = self.importForcastLongFromYrInJson( "Norge/Trøndelag/Trondheim/Trondheim/") formated_data = self.formatDataFromYrToJson(imported_data) send_data = self.mqttSend(formated_data) return send_data
def _generate_svg(): ''' Modifies the svn with the information we want :return: ''' print('func _generate_svg') # @todo Add timezone as setting d = datetime.now() + timedelta(hours=1) today = d.strftime("%A %d.%m - kl %H:%M:%S") # Open SVG to process output = codecs.open('static/templates/landscape.svg', 'r', encoding='utf-8').read() # Insert icons and temperatures output = output.replace('Today', today) # Set times t = _find_time(d) print('t', t) output = output.replace('Time_0', "%i%s" % ((t[0]),':00')) output = output.replace('Time_1', "%i%s" % ((t[1]),':00')) output = output.replace('Time_2', "%i%s" % ((t[2]),':00')) forecasts = [] #weather = Yr(location_name='Norge/Telemark/Skien/Skien') #now = weather.now(as_json=True) weather = Yr(location_name='Norge/Telemark/Skien/Skien', forecast_link='forecast_hour_by_hour') for forecast in weather.forecast(as_json=True): f = json.loads(forecast) yourdate = dateutil.parser.parse(f['@from']) #print('aaa2', yourdate.hour) if yourdate.hour in t: forecasts.append(f) # Insert temperature output = output.replace('Temp_0', "%s%s" % (forecasts[0]['temperature']['@value'], '°C')) output = output.replace('Temp_1', "%s%s" % (forecasts[1]['temperature']['@value'], '°C')) output = output.replace('Temp_2', "%s%s" % (forecasts[2]['temperature']['@value'], '°C')) print('forecasts 0', forecasts[0]) print('forecasts 1', forecasts[1]) print('forecasts 2', forecasts[2]) # Insert symbols n = forecasts[0]['symbol']['@var'] s = "static/symbols/%s.svg" % (n) symbol = codecs.open(s, 'r', encoding='utf-8').read() symbol = symbol.replace('viewBox="0 0 100 100"', "%s" % ('viewBox="0 0 800 600"')) output = output.replace('<text>Icon_1</text>', "%s" % (symbol)) print('s', s) n = forecasts[1]['symbol']['@var'] s = "static/symbols/%s.svg" % (n) symbol = codecs.open(s, 'r', encoding='utf-8').read() symbol = symbol.replace('viewBox="0 0 100 100"', "%s" % ('viewBox="0 0 800 600"')) output = output.replace('<text>Icon_2</text>', "%s" % (symbol)) print('s', s) n = forecasts[1]['symbol']['@var'] s = "static/symbols/%s.svg" % (n) symbol = codecs.open(s, 'r', encoding='utf-8').read() symbol = symbol.replace('viewBox="0 0 100 100"', "%s" % ('viewBox="0 0 800 600"')) output = output.replace('<text>Icon_3</text>', "%s" % (symbol)) print('s', s) #output = output.replace('<text>Icon_1</text>', "%s" % (symbol)) # for idx, val in enumerate(t): # print(idx, val) print('find time, ', t) # Write output filename = 'static/after-weather.svg' codecs.open(filename, 'w', encoding='utf-8').write(output) return filename
log = sys.argv[2] requestType = int(sys.argv[3]) asJSON = bool("foo") if sys.argv[4] == "F": asJSON = bool("") weather = "" #Get the weather forecast for the specified location if requestType == 1: weather = Yr(location_name='Norway/Rogaland/Stavanger/Stavanger') #Get the hourly weather forecast for the specified location elif requestType == 2: weather = Yr(location_name='Norway/Rogaland/Stavanger/Stavanger', forecast_link='forecast_hour_by_hour') #Get the current forecast for the specified location else: weather = Yr(location_name='Norway/Rogaland/Stavanger/Stavanger') weatherResponse = "" if requestType != 0: if (asJSON): for forecast in weather.forecast(as_json=asJSON): weatherResponse += forecast else: weatherResponse = weather else: weatherResponse = weather.now(as_json=asJSON) print(weatherResponse)
#dT/dt=-k(T-Ta) --> T(t) = Ce^-(kt)+Ta #T_r1 = Reell innrtemperatur målt av sensor ved tidspunkt 1 #T_r2 = Reell innrtemperatur målt av sensor ved tidspunkt 2 #T_e = estimert innetemperatur fra x minnutter før #T_u = utetemperatur #dt = tidsintervall mellom tidspunkt 1 og tidspunkt 2 #C regnes enkelt ut #k regnes ut ################################################################################################################### from yr.libyr import Yr import json info = {} weather = Yr(location_name='Norway/Oslo/Oslo/Oslo', forecast_link='forecast_hour_by_hour') for forecast in weather.forecast( str): #for alle 'forecast i weather.forecastene data = json.loads(forecast) #Last inn værdata print(data['symbol']) tempStr = data['temperature'][ '@value'] #henter ut verdien temp verdien som streng tempInt = int(tempStr) #gjør til int rtime = data[ '@from'] #Tar ut tidsstempelet fra timen som blir gitt ut til neste time info[rtime] = { '@time': rtime, '@temp': tempInt } #markerer hvert data sett med unik datokode og Legger tidsdataen i et dict og tar med all tidsdata for neste 24t i et stort dict ######################################################################################################################
#!/usr/bin/env python3 from yr.libyr import Yr weather = Yr(location_name='Norge/Telemark/Skien/Skien') for forecast in weather.forecast(as_json=True): print(forecast)
# https://github.com/wckd/python-yr from yr.libyr import Yr import json # henter værvarsel for Sinsen for neste 48 timer, time for time weather_Sinsen = Yr(location_name='Norway/Oslo/Oslo/Sinsen', forecast_link='forecast_hour_by_hour') # lager lister som blir brukt til verdier i for-løkken under tid_lst_Sinsen = [] temp_lst_Sinsen = [] wind_lst_Sinsen = [] rain_lst_Sinsen = [] # itirerer json telegrammet og legger verdier i lister for forecast in weather_Sinsen.forecast(str): data = json.loads(forecast) tid = data['@from'] tid_lst_Sinsen.append(tid) temperature = data['temperature'] all_temps = temperature['@value'] temp_lst_Sinsen.append(all_temps) wind = data['windSpeed'] all_wind = wind['@mps'] wind_lst_Sinsen.append(all_wind) rain = data['precipitation'] all_rain = rain['@value'] rain_lst_Sinsen.append(all_rain) # gjør om liste til array,gjør så om string array til float array tid_arr_Sinsen = np.array(tid_lst_Sinsen)
#!/usr/bin/env python3 from yr.libyr import Yr weather = Yr(location_name='Norge/Telemark/Skien/Skien') wind_speed = dict() wind_speed['data'] = [{'from': forecast['@from'], 'to': forecast['@to'], 'speed': float(forecast['windSpeed']['@mps'])} for forecast in weather.forecast()] wind_speed['credit'] = weather.credit print(wind_speed)
def hourly_summary(self) -> pd.DataFrame: """Creates a 48 hour forecast summary""" data = Yr(location_name=self.location, forecast_link='forecast_hour_by_hour') return pd.DataFrame([self._process_data(x) for x in data.forecast()])