Ejemplo n.º 1
0
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
Ejemplo n.º 2
0
def get_weather():
    weather_df = Yr(location_name='Norge/Trøndelag/Trondheim/Trondheim')
    now_df = weather_df.now() # henter værdata fra Yr
    temp_val = int(pd.DataFrame(now_df)['temperature']['@value']) # finner luft temeperaturen
    wind_val = float(pd.DataFrame(now_df)['windSpeed']['@mps']) # finner vindfart
#    wind_dir = float(pd.DataFrame(now_df)['windDirection']['@deg'])
    precipitation_val = float(pd.DataFrame(now_df)['precipitation']['@value']) # finner regn
#Sends temp, windspeed and precipitation to CoT

    token = 'eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1NzUxIn0.DeRcDo1IRe0fFV_IEw8WyUbEd02hwzWikjARXvc2oEE'
    
    temp_key = '12583'
    temp_data = {'Key': temp_key, 'Value': temp_val, 'Token': token} # sender lufttemp til CoT
    t_put = requests.put('https://circusofthings.com/WriteValue', 
             data = json.dumps(temp_data), 
             headers={'Content-Type': 'application/json'})
    
    wind_key = '8760'
    wind_data = {'Key': wind_key, 'Value': wind_val, 'Token': token} # sender vindfart til CoT
    w_put = requests.put('https://circusofthings.com/WriteValue', 
             data = json.dumps(wind_data), 
             headers={'Content-Type': 'application/json'})
    
    precipitation_key = '6464'
    precipitation_data = {'Key': precipitation_key, 'Value': precipitation_val, 'Token': token} # sender regn til CoT
    p_put = requests.put('https://circusofthings.com/WriteValue', 
             data = json.dumps(precipitation_data), 
             headers={'Content-Type': 'application/json'})
#sende data til cot
Ejemplo n.º 3
0
 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()
Ejemplo n.º 4
0
def weather_data():
    # Henter temperaturen og værtypen fra yr for videre bruk for å finne værfaktor og modul effektivitet
    weather_json = Yr(location_name="Norge/Trøndelag/Trondheim/Trondheim"
                      )  # henter vær data fra Yr
    now_json = weather_json.now()
    temp_now = int(
        pd.DataFrame(now_json)["temperature"]["@value"])  # temperatur
    cloud_typ = (pd.DataFrame(now_json)["symbol"]["@name"])  # skydekke

    return [temp_now, cloud_typ]
Ejemplo n.º 5
0
 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
Ejemplo n.º 6
0
 def __init__(self, codigo):
     site       = locationSite(codigo)
     weather    = Yr(site)
     main       = weather.now()
     if (main):
         self.wdb.setMeasure('pressure'        , main['pressure']     ['@value']    )
         self.wdb.setMeasure('temperature'     , main['temperature']  ['@value']    )
         self.wdb.setMeasure('weatherMain'     , main['symbol']       ['@name']     )
         self.wdb.setMeasure('windSpeed'       , float(main['windSpeed']    ['@mps']) * 3.6)
         self.wdb.setMeasure('windMain'        , main['windSpeed']     ['@name']     )
         self.wdb.setMeasure('windDegrees'     , main['windDirection']['@deg']      )
         self.wdb.setMeasure('rainProbability' , main['precipitation']['@value']    )
         self.wdb.setMeasureClean()
Ejemplo n.º 7
0
 def __init__(self, city):
     self.weather = Yr(location_name=city)
     self.now = self.weather.now()
     self.symbol = self.now['symbol']['@var']
     self.precipitation = self.now['precipitation']['@value']
     self.windDirection = self.now['windDirection']['@code']
     self.windSpeed = self.now['windSpeed']['@mps']
     self.temperature = self.now['temperature']['@value']
     self.pressure = self.now['pressure']['@value']
     if self.windDirection in wind_direction_arrow.keys():
         self.wind_direction_arrow_icon = wind_direction_arrow[
             self.windDirection]
     else:
         self.wind_direction_arrow_icon = ''
Ejemplo n.º 8
0
    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 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
Ejemplo n.º 10
0
    def get_weather(self):
        '''Gets the object from the weather API library based on a given latitude and longitude.

        Returns:
            :obj:`tuple`: An instance of Yr from the yr.no library (weather API).'''
        geo = self._get_geolocation('ba8e737cd1ce0e3bf0ede0cd1caeea68')
        weather = Yr(location_xyz=(geo[1], geo[0], 0))

        return weather
Ejemplo n.º 11
0
    def importForcastTodayFromYrInJson(self, place_string):
        """Import 8todays 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 

        """

        weather_import = Yr(location_name=place_string)
        weather_now_json = weather_import.now(as_json=True)
        weather_now = json.loads(weather_now_json)
        print(weather_now)
        return weather_now
Ejemplo n.º 12
0
def heating_house():  #assume 2 panel ovens (Living room and hallway)
    weather_df = Yr(location_name='Norge/Trøndelag/Trondheim/Trondheim')
    now_df = weather_df.now()
    date = dt.datetime.now().strftime('%d-%m-%y')  # henter vær og dato
    temp_df = pd.read_csv('temp_csv/Heating_Room.csv',
                          index_col='Date').at[date,
                                               'Temp']  # henter temperatur
    temp_val = sum(temp_df) / len(temp_df)
    temp_val = int(pd.DataFrame(now_df)['temperature']
                   ['@value'])  # finner lufttemperatur som heltall

    if temp_val < 22:  # finner ut hvor mye energi som brukes til oppvarming
        energy_house = (room_heating * (22 - temp_val)) * 2
    else:
        energy_house = 0
    if temp_val < 28:
        energy_bath = (room_heating * (28 - temp_val))
    else:
        energy_bath = 0
    return [energy_house, energy_bath]
Ejemplo n.º 13
0
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)
Ejemplo n.º 14
0
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)
Ejemplo n.º 15
0
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)
Ejemplo n.º 16
0
class YrNow(object):
    def __init__(self, city):
        self.weather = Yr(location_name=city)
        self.now = self.weather.now()
        self.symbol = self.now['symbol']['@var']
        self.precipitation = self.now['precipitation']['@value']
        self.windDirection = self.now['windDirection']['@code']
        self.windSpeed = self.now['windSpeed']['@mps']
        self.temperature = self.now['temperature']['@value']
        self.pressure = self.now['pressure']['@value']
        if self.windDirection in wind_direction_arrow.keys():
            self.wind_direction_arrow_icon = wind_direction_arrow[
                self.windDirection]
        else:
            self.wind_direction_arrow_icon = ''

    def __str__(self):
        return f"Сейчас 🌡 {self.temperature}°C, Давление {self.pressure}, ☂️ {self.precipitation}мм, "\
               f"🌬 {self.wind_direction_arrow_icon} {self.windSpeed}м/с\n\n"
Ejemplo n.º 17
0
    return pris
        
    
InCur= 'EUR'
OutCur= 'NOK'

Multiple=Currency_Rate(InCur,OutCur)
Price=Day_Ahead_Prices()
    
PriceOutCur=np.array(Price)*Multiple    #liste med pris i 48 timer

#########################################################################################################################
#YR GET

info = {}
weather = Yr(location_name='Norway/Telemark/Skien/Skien', 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
        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

###########################################################################################################################
#Sortete de neste 24 timene
        
#lager timestamps for 2 neste døgn,1. døgn er nåværende
timestamp=[]
for x in range(0,48):
    timestamp.append(pendulum.today().add(hours=x).strftime('%Y-%m-%dT%H:%M:%S'))
Ejemplo n.º 18
0
#!/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)
Ejemplo n.º 19
0
#!/usr/bin/env python3

#import json
from yr.libyr import Yr

weather = Yr(location_name='Croatia/Zagreb_fylke/Samobor')

first = 0

for forecast in weather.forecast(as_json=True):
    print(forecast)
#    x = json.loads(forecast)

#    if first == 0:
#        first = 1;
#        print(x)
#    elif x["@period"] == "1":
#        print(x)
Ejemplo n.º 20
0
 def __init__(self):
     self.weather_api = Yr(self.location)
Ejemplo n.º 21
0
def forecast_for(location):
    return Yr(location_name=location, forecast_link='forecast_hour_by_hour').dictionary
Ejemplo n.º 22
0
from yr.libyr import Yr
import datetime

try:
    yr = Yr(location_name='Norge/Sør-Trøndelag/Trondheim/Trondheim')
except RuntimeWarning:
    print("Whoops, something went wrong with fetching your yr!")
    pass


class weather:
    def weatherNow(self):
        now = yr.now(as_json=False)
        weatherDict = {
            "temp": now['temperature']['@value'],
            "precipitation": now['precipitation']['@value'],
            "windDir": now['windDirection']['@code'],
            "windSpeed": now['windSpeed']['@mps'],
            "symbol": now['symbol']['@var']
        }
        return weatherDict

    def weatherForcast(self):
        forecastArray = []
        for forecast in yr.forecast():
            time = datetime.datetime.strptime(forecast['@from'],
                                              "%Y-%m-%dT%H:%M:%S")
            dayName = ["Man", "Tir", "Ons", "Tor", "Fre", "Lør", "Søn"]
            forecastArray.append({
                # readable datetime
                "time":
Ejemplo n.º 23
0
#!/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(as_json=True):
    print(forecast)
Ejemplo n.º 24
0
#!/usr/bin/env python3

from yr.libyr import Yr

weather = Yr(location_name="Italy/Trentino_and_South-Tirol/San_Michele_all'Adige")
#weather = Yr(location_xyz=(11.13358, 46.19291, 210)) # xyz for Italy/Trentino_and_South-Tirol/San_Michele_all'Adige

weather.py2csv() # print to stdout all values
print()
weather.py2csv(daily=True) # print to stdout daily values
Ejemplo n.º 25
0
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)
Ejemplo n.º 26
0
#!/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)
Ejemplo n.º 27
0
  print("usage: ./getWeather latitude longitude requestType asJSON")
  print("locationName=latitude, longitude, requestType=0:Now, 1:Forecast, 2:HourlyForecast, asJSON=T:asJSONString, F:asDictionaryObject")
  exit()	

lat=sys.argv[1]
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:
Ejemplo n.º 28
0
#!/usr/bin/python3

# pip3 install python-yr

from yr.libyr import Yr

weather = Yr(location_name='Germany/Berlin/Berlin')
data = weather.now()

weather = data['symbol']['@name']
temperature = data['temperature']['@value']

print("<fc=#FFFFFF>%s %s °C</fc>" % (weather, temperature))
Ejemplo n.º 29
0
#!/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)
Ejemplo n.º 30
0
#Modellerer varmetap med newtons varmetaps likning

#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
Ejemplo n.º 31
0
class WindLocator(object):
    WORK_DAY = range(0, 5)  # Mon - Fri
    WEEKEND = range(5, 7)  # Sat, Sun
    location = 'Norge/Akershus/Bærum/Halden_brygge'
    time_limits = {WORK_DAY: 16, WEEKEND: 8}
    wind_limit = 5.0  # m/s
    username = input('Email address:')
    password = getpass()

    def __init__(self):
        self.weather_api = Yr(self.location)

    def get_interesting_hour(self):
        '''
        This method tells us at after what hour in the day
        we are interested in getting wind data
        '''
        day_of_week = (datetime.today() + timedelta(days=1)).weekday()
        for weekdays, time in self.time_limits.items():
            if day_of_week in weekdays:
                return time

    def sort_time_data(self, intervals):
        '''
        Sort by time of day, but only show today's date
        '''
        interesting_day = datetime.today().date() + timedelta(days=1)
        for interval in intervals:
            date = parse(interval['from']).date()
            if date == interesting_day:
                yield interval

    def run(self):
        print('[~] Getting weather data')
        now_json = self.weather_api.wind_speed()['data']
        print('[~] Got weather data')
        limit = self.get_interesting_hour()
        intervals = self.sort_time_data(now_json)
        for time_interval in intervals:
            if parse(time_interval['from']).time().hour < limit:
                continue
            if time_interval['speed'] > self.wind_limit:
                self.send_message(time_interval)
                return

    def send_message(self, interval):
        msg = MIMEText('Wind alert: %s\nFrom %s to %s\nWindspeed: %s'
                       % (self.location, interval['from'], interval['to'],
                          interval['speed']))
        msg['Subject'] = ('Wind looks good: (%s) %s at %s'
                          % (self.location, interval['speed'],
                             interval['from']))
        msg['From'] = self.username
        msg['To'] = self.username

        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.ehlo()
        server.starttls()
        server.ehlo()
        server.login(self.username, self.password)
        server.send_message(msg)
        server.close()
        print('[~] Sent Message')
Ejemplo n.º 32
0
#!/usr/bin/env python3

from yr.libyr import Yr

#weather = Yr(location_name="Italy/Trentino_and_South-Tirol/San_Michele_all'Adige")
weather = Yr(location_xyz=(
    11.13358, 46.19291,
    250))  # xyz for Italy/Trentino_and_South-Tirol/San_Michele_all'Adige

for forecast in weather.forecast(as_json=True):
    print(forecast)
Ejemplo n.º 33
0
def heating_bedroom():
    # Henter værdata for tiden akkurat nå fra yr.
    weather_df = Yr(location_name='Norge/Trøndelag/Trondheim/Trondheim')
    now_df = weather_df.now()

    # Trekker ut utetemperaturen som skal brukes til å regne strømforbruk.
    temp_val = int(pd.DataFrame(now_df)['temperature']['@value'])

    # Definerer oppvarmingskoeffisient i kWh/(C*h).
    # Brukes for å finne strømforbruket for den gjellende timen basert på utetemp.
    room_heating = 0.0146  #kWh/(C*h)

    # Definerer den gjellenge dagen
    date = dt.datetime.now().strftime("%d-%m-%y")
    # Definerer den gjellende timen
    hour = int(dt.datetime.now().strftime("%H"))

    # Definerer signal key for termostat temperaturen og hjemme status som hentes fra CoT.
    temp_key = '6074'
    room_key = '15089'
    # Definerer token for å hente info fra CoT
    token = 'eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1NzUxIn0.DeRcDo1IRe0fFV_IEw8WyUbEd02hwzWikjARXvc2oEE'

    # Henter ut termostat verdien celsius til soverommet fra CoT
    # og lagrer verdien i en variabel som skal brukes for å finne strømforbruket.
    t = requests.get('https://circusofthings.com/ReadValue',
                     params={
                         'Key': temp_key,
                         'Token': token
                     })
    temp_room = round(json.loads(t.content)['Value'])

    # Henter ut hjemme status verdien til soverommet fra CoT
    # og lagrer verdien i en variabel som skal brukes for å finne strømforbruket. (1 = hjemme, 0 = borte)
    r = requests.get('https://circusofthings.com/ReadValue',
                     params={
                         'Key': room_key,
                         'Token': token
                     })
    ishome = json.loads(r.content)['Value']

    # Finner strømforbruket på dagen (kl. 07:00 til 23:00) når beboeren er hjemme
    if ishome == 1 and hour != 23 and hour not in range(0, 8):
        # Hvis termostaten har blitt satt til 0 betyr det at ovnen er skrudd av og bruker ikke strøm.
        if (temp_room == 0):
            energy_bedroom = 0
        # Når utetemp er lavere enn verdien til termostaten blir
        # differansen ganget med koeffisienten for å finne strømforbruket til panelovnen.
        elif (temp_val < temp_room):
            energy_bedroom = room_heating * (temp_room - temp_val)
        # Når utetemp er lik eller større enn verdien til termostaten bruker ikke panelovnen strøm.
        else:
            energy_bedroom = 0

    # Når beboeren er borte, bruker ikke panelovnen strøm.
    elif ishome == 0:
        energy_bedroom = 0

    # Finner strømforbruket når beboeren er hjemme på natta (kl 23:00 til 06:00).
    elif (hour == 23 or hour in range(0, 7)) and ishome == 1:
        # Hvis termostaten har blitt satt til 0 betyr det at ovnen er skrudd av og bruker ikke strøm.
        if (temp_room == 0):
            energy_bedroom = 0
        # Når utetemp er mindre enn termostat verdien minus 4 blir differansen
        # (termostat verdi – 4 – utetemp) ganget med koeffisienten for å finne strømforbruket til panelovnen.
        # Dette blir gjort for å simulere mindre strømforbruk om natta.
        elif (temp_val < temp_room - 4):
            energy_bedroom = room_heating * ((temp_room - 4) - temp_val)
        # Når utetemp er lik eller større enn verdien til termostaten minus 4 bruker ikke panelovnen strøm.
        else:
            energy_bedroom = 0

    # Runder av verdien for å bli kvitt unødvendige desimaltell.
    energy_bedroom = round(energy_bedroom, 3)

    # Skriver srtømdorbruket, temperaturen og datoen til en csv_fil.
    # Strømforbruksverdien blir brukt i el_forbruk til å regen ut totalt strømforbruk for rommet den gjellende dagen.
    # Tenperatur verdien blir brukt i el_forbruk for å finne gjennomsnittstemperaturen for dagen
    # som igjenn blir brukt for å finne strømforbruket til fellesarealene.
    with open('temp_csv/Heating_Room.csv', 'a') as p:
        prod_df = csv.writer(p)
        prod_df.writerow([date, energy_bedroom, temp_val])

    hr = pd.read_csv('temp_csv/Heating_Room.csv')
    return hr
#!/usr/bin/env python3

from yr.libyr import Yr

#weather = Yr(location_name="Italy/Trentino_and_South-Tirol/San_Michele_all'Adige")
weather = Yr(location_xyz=(11.13358, 46.19291, 210)) # xyz for Italy/Trentino_and_South-Tirol/San_Michele_all'Adige

all_parameters = [ # from the api is possible to obtain more info
    'humidity',
    'cloudiness',
    'lowClouds',
    'mediumClouds',
    'highClouds',
    'dewpointTemperature',
    'precipitation',
    'windDirection',
    'windSpeed',
    'temperature',
    'pressure',
]

weather.py2csv(parameters=all_parameters) # print to stdout all values
print()
weather.py2csv(daily=True, parameters=all_parameters) # print to stdout daily values
Ejemplo n.º 35
0
import bs4
import os
from nltk.corpus import wordnet as wn
from bs4 import BeautifulSoup as soup
from time import gmtime, strftime
from googlesearch import search
from pygame import mixer
from yr.libyr import Yr
from lxml import etree

os.system('cls' if os.name == 'nt' else 'clear')

engine = pyttsx3.init()
engine.setProperty('rate', 140)

weather = Yr(location_name='South_Africa/KwaZulu-Natal/Durban/'
             )  #Fill in your own location. More help in readme.md

r = sr.Recognizer()
r.dynamic_energy_threshold = False

engine.say(
    "I am cashew, a TTS Virtual assistant, clap before talking so I can hear you, say cashew to turn me on"
)
engine.runAndWait()

microphone_index = 2  #Change this to whatever audio channel your microphone is on.


def onnoise():
    mixer.init()
    mixer.music.load(
Ejemplo n.º 36
0
#!/usr/bin/env python3

from yr.libyr import Yr

weather = Yr(location_name='Norge/Telemark/Skien/Skien')

print(weather.xml_source)
Ejemplo n.º 37
0
 def get_forecast(self, place, kickoff, tz):
     for forecast in Yr(location_name=place).forecast():
         forecast = self.localize_times(forecast, tz)
         if forecast['@from'] <= kickoff < forecast['@to']:
             self.logger.debug("Found weather %r", forecast)
             return forecast
Ejemplo n.º 38
0
#!/usr/bin/env python3

from yr.libyr import Yr

weather = Yr(location_name='Norge/Telemark/Skien/Skien')
now = weather.now(as_json=True)

print(now)
Ejemplo n.º 39
0
#!/usr/bin/env python3

from yr.libyr import Yr

weather = Yr(location_name='Norge/Telemark/Skien/Skien')
now = weather.now()

print(now)