Ejemplo n.º 1
0
def get_current_weather_data(lat, long):
    """
    Given a location, get the weather data for the next 48 hrs.
    :param lat: latitude
    :param long: longitude
    :return: list of hourly weather data for the given lat long
    """
    darksky = DarkSky(DARKSKY)
    try:
        # get the data
        forecast = darksky.get_forecast(
            lat, long,
            exclude=[weather.HOURLY, weather.MINUTELY,
                     weather.DAILY, weather.ALERTS, weather.FLAGS])

        # add lat & long to the hourly weather data for composite key in db
        data = forecast.currently
        data.latitude = lat
        data.longitude = long
        data = data.__dict__
        data.pop("time")
        return data
    except Exception as e:
        print(e)
        return None
Ejemplo n.º 2
0
def index():
    geolocator = Nominatim(user_agent="MJGEo")
    location = geolocator.geocode("Patna")
    mloc = location
    API_KEY = 'e2fea81b36c2588f1315c4ad2b721989'
    darksky = DarkSky(API_KEY)
    latitude = location.latitude
    longitude = location.longitude
    forecast = darksky.get_forecast(
        latitude,
        longitude,
        extend=False,  # default `False`
        lang=languages.HINDI,  # default `ENGLISH`
        units=units.AUTO,  # default `auto`
        exclude=[weather.MINUTELY, weather.ALERTS]  # default `[]`
    )

    icon = forecast.currently.icon
    temperature = forecast.currently.temperature
    print(temperature)
    print(forecast.timezone)
    forecast.latitude  # 42.3601
    forecast.longitude  # -71.0589
    forecast.timezone  # timezone for coordinates. For exmaple: `America/New_York`

    forecast.currently  # CurrentlyForecast. Can be finded at darksky/forecast.py
    forecast.minutely  # MinutelyForecast. Can be finded at darksky/forecast.py
    forecast.hourly  # HourlyForecast. Can be finded at darksky/forecast.py
    forecast.daily  # DailyForecast. Can be finded at darksky/forecast.py
    forecast.alerts  # [Alert]. Can be finded at darksky/forecast.py
    params = {'sloc': mloc}
    return render_template("index.html",
                           name=mloc,
                           icon=icon,
                           temperature=temperature)
Ejemplo n.º 3
0
def get_hourly_weather_data(lat, long):
    """
    Given a location, get the weather data for the next 48 hrs.
    :param lat: latitude
    :param long: longitude
    :return: list of hourly weather data for the given lat long
    """
    darksky = DarkSky(DARKSKY)
    try:
        # get the data
        forecast = darksky.get_forecast(
            lat, long,
            exclude=[weather.CURRENTLY, weather.MINUTELY,
                     weather.DAILY, weather.ALERTS, weather.FLAGS])

        # add lat & long to the hourly weather data for composite key in db
        hourly_weather_data = []
        for data in forecast['hourly']['data']:
            data['latitude'] = lat
            data['longitude'] = long
            hourly_weather_data.append(data)

        # Lets save the weather data while were at it
        # for data in hourly_weather_data:
        #     db.weather_container.create_item(data)

        return hourly_weather_data
    except Exception as e:
        print(e)
        return None
Ejemplo n.º 4
0
def get_weather():
    darksky = DarkSky(DARKSKY_API_KEY)
    forecast = darksky.get_forecast(latitude, longitude)
    todays_forecast = forecast.daily.data[0]
    summary = todays_forecast.summary
    temp_high = str(round(todays_forecast.temperature_high))
    temp_low = str(round(todays_forecast.temperature_low))
    return summary, temp_high, temp_low
Ejemplo n.º 5
0
def weather_data(lat, long, api_key):
    darksky = DarkSky(api_key)
    logger.info("Powered by Dark Sky")
    forecast = darksky.get_forecast(lat,
                                    long,
                                    extend=False,
                                    lang=languages.ENGLISH,
                                    values_units=units.AUTO,
                                    exclude=[weather.ALERTS, weather.MINUTELY])
    return forecast
Ejemplo n.º 6
0
def dashboard(request):

    client_ip = get_client_ip(request)

    try:
        user = User.objects.get(client_ip=client_ip[0])
    except:
        user = User()

    #Grabs the IP from api.ipify.org which can be found in GeoIP2's API
    remote_ip_cache = cache.get('remote_ip')  # or user.last_ip
    remote_ip = requests.get(url='https://api.ipify.org')

    #Instead of storing in the database, we can just use the user's cache to store their content
    if (remote_ip_cache == None):
        cache.set('remote_ip', remote_ip)
    #If the ip that we get from api.ipify.org is different than the cache/data model
    #We can assume that they have relocated and we will try and update their location based
    #off the GeoIP API
    if (remote_ip_cache != remote_ip):
        cache.set('remote_ip', remote_ip)
        remote_ip_cache = remote_ip

    user.last_ip = remote_ip_cache.text
    g = GeoIP2()

    try:
        lat_lon = g.lat_lon(remote_ip_cache.text)
        user.last_latitude = lat_lon[0]
        user.last_longitude = lat_lon[1]
    except:
        raise Http404("Can not find Location.")

    #We could make some logic to only allow these users to get requests from Dark Sky API
    # every so often.
    user.last_request = timezone.now()
    user.save()

    geoCity = g.city(remote_ip.text)

    #Get Forecast from Dark Sky API with API_KEY
    DWD_API_KEY = '9e3ac71786112191eaed1cd8abbe4614'
    darksky = DarkSky(DWD_API_KEY)

    forecast = darksky.get_forecast(
        lat_lon[0],
        lat_lon[1],
        extend=False,  # default `False`
        lang=languages.ENGLISH,  # default `ENGLISH`
        units=units.AUTO,  # default `auto`
        exclude=[weather.MINUTELY, weather.ALERTS]  # default `[]`
    )

    context = {'forecast': forecast, 'geoCity': geoCity}
    return render(request, 'weatherApp/dashboard.html', context)
Ejemplo n.º 7
0
def weatherinfo(lat,long_):
    api ='af654ddc453104adcc9b4d0818a7604d' # this is mine, its is possible to get your own if you ready have an darksky acc...or..
    dsky = DarkSky(api)                     # its not possible coz...darksky stopped creating new APIs since it is aquired by apple
    forecast = dsky.get_forecast(
        lat,long_,
        extend=False,
        lang=languages.ENGLISH,
        values_units= units.SI,
        exclude=[weather.MINUTELY,weather.HOURLY,weather.ALERTS,weather.FLAGS]
    )
    return forecast
Ejemplo n.º 8
0
def get_DS_forecasts(latitude, longitude):
    darksky = DarkSky(API_KEY)
    forecast = darksky.get_forecast(latitude,
                                    longitude,
                                    exclude=[weather.MINUTELY, weather.FLAGS])

    # weather now, +[3/6/9/12] hour forecasts
    everyThreeHours = {}
    everyThreeHours[str(0)] = forecast.currently
    for i in range(1, 5):
        idx = 3 * i
        everyThreeHours[str(i)] = forecast.hourly.data[idx]

    return (everyThreeHours, forecast.alerts)
Ejemplo n.º 9
0
def main(api_key, lat, long):

    # log in home dir
    logging.basicConfig(
        filename=PurePath(Path.home()).joinpath('logs/cloud.log'),
        level=logging.DEBUG,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    pi_led = RGBLED(red=17, green=27, blue=24, pin_factory=PiGPIOFactory())
    darksky = DarkSky(api_key)
    forecast = darksky.get_forecast(
        lat, long, exclude=['minutely', 'hourly', 'daily', 'alerts',
                            'flags']).currently.icon
    logging.info('Icon: {}'.format(forecast))
    weather_indicator(pi_led, WEATHER_COLOR_MAP.get(forecast, 'unknown_icon'))
Ejemplo n.º 10
0
def setValues():
    location = str(city.get())
    if location[-3:] == 'usa':
        usa = 1
    else:
        usa = 0
    # Geocoding the city using GoogleMaps API
    geocode_result = gmaps.geocode(location)
    lat = geocode_result[0]['geometry']['location']['lat']
    lng = geocode_result[0]['geometry']['location']['lng']

    # set up darksky API to retreave weather data
    darksky = DarkSky(skyAPI)
    forecast = darksky.get_forecast(
        lat,
        lng,
        extend=False,  # default `False`
        lang=languages.ENGLISH,  # default `ENGLISH`
        units=units.AUTO,  # default `auto`
        exclude=[weather.MINUTELY, weather.ALERTS]  # default `[]`
    )

    # set the variables for display
    wind.set(str(round(forecast.currently.wind_speed, 2)) + 'mph')
    updated.set(str(forecast.currently.time)[:-6])
    weathers.set(forecast.currently.summary)
    if usa == 0:
        tempC = round(forecast.currently.temperature)
        tempF = round(forecast.currently.temperature * 1.8 + 32)
    else:
        tempF = round(forecast.currently.temperature)
        tempC = round((forecast.currently.temperature - 32) / 1.8)
    temp.set(str(int(tempC)) + '℃ ' + str(int(tempF)) + '℉ ')
    relHum.set(str(int(forecast.currently.humidity * 100)) + '%')
    visibility.set(str(round(forecast.currently.visibility, 2)) + 'miles')
    if str(forecast.currently.precip_type) == 'None':
        prec.set(str(forecast.currently.precip_type))
    else:
        prec.set(
            str(int(forecast.currently.precip_probability)) + "% " +
            str(forecast.currently.precip_type))
    uv.set(str(int(forecast.currently.uv_index)))
    if usa == 0:
        dewC = round(forecast.currently.dew_point)
        dewF = round(forecast.currently.dew_point * 1.8 + 32)
    else:
        dewF = round(forecast.currently.dew_point)
        dewC = round((forecast.currently.dew_point - 32) / 1.8)
    dew.set(str(int(dewC)) + '℃ ' + str(int(dewF)) + '℉ ')
Ejemplo n.º 11
0
def get_temperature(location={"lat": 31.630000, "long": -8.008889}):
    # Synchronous way
    darksky = DarkSky(API_KEY)

    latitude = location['lat']
    longitude = location['long']
    forecast = darksky.get_forecast(
        latitude,
        longitude,
        extend=False,  # default `False`
        lang=languages.ENGLISH,  # default `ENGLISH`
        units=units.AUTO,  # default `auto`
        exclude=[weather.MINUTELY, weather.ALERTS]  # default `[]`
    )
    return forecast.currently.temperature
Ejemplo n.º 12
0
 def extract_data(self, message):
     darksky = DarkSky("68a391b503f11aa6fa13d405bfefdaba")
     latitude = message['latitude']
     longitude = message['longitude']
     forecast = darksky.get_forecast(
         latitude, longitude,
         extend=False, 
         lang=languages.ENGLISH,
         values_units=units.AUTO, 
         exclude=[weather.MINUTELY, weather.ALERTS], 
         timezone='UTC'
     )
     current = forecast.currently
     mssg = {'summary':current.summary, 
             'windSpeed':current.wind_speed,
             'humidity':current.humidity,
             'temperature':current.temperature}
     return mssg
Ejemplo n.º 13
0
class WeatherFetcher:
    def __init__(self):
        self.data: Forecast = None
        self._lock = threading.Lock()
        self.darksky = DarkSky(dark_sky_key)

    def do(self):
        forecast = self.darksky.get_forecast(dark_sky_lat, dark_sky_lon)
        self.update(forecast)
        print(forecast.currently.temperature)

    def update(self, data: Forecast):
        with self._lock:
            self.data = data

    def read(self):
        with self._lock:
            return self.data
Ejemplo n.º 14
0
def get_weather(latlong=latlong):
    from darksky.api import DarkSky, DarkSkyAsync
    from darksky.types import languages, units, weather

    API_KEY = get_API_from_file()

    # Synchronous way
    darksky = DarkSky(API_KEY)
    #print (latlong)
    latitude, longitude = latlong  #[:]
    forecast = darksky.get_forecast(
        latitude,
        longitude,
        extend=False,  # default `False`
        lang=languages.ENGLISH,  # default `ENGLISH`
        #values_units= units.AUTO, # default auto
        exclude=[weather.MINUTELY],  # weather.ALERTS] - default []
    )
    return forecast
Ejemplo n.º 15
0
    def get_forecast(self, coordinate):
        API_KEY = self.config.get_config('darksky', 'api', '9bd0b8315895a1c550505b281fc082ff')

        # Synchronous way
        darksky = DarkSky(API_KEY)

        #latitude = 42.3601
        #longitude = -71.0589
        latitude, longitude = coordinate
        forecast = darksky.get_forecast(
            latitude, longitude,
            extend=False, # default `False`
            lang=languages.ENGLISH, # default `ENGLISH`
            values_units=units.AUTO, # default `auto`
            exclude=[weather.MINUTELY, weather.ALERTS], # default `[]`,
            timezone='Asia/Jakarta' # default None - will be set by DarkSky API automatically
        )
        print(forecast)
        return forecast
Ejemplo n.º 16
0
    def update_weather(self):
        # Get weather
        print("Updating weather:")
        darksky = DarkSky(self.darksky_secret)
        try:
            self.forecast = darksky.get_forecast(43.312691,
                                                 -1.993332,
                                                 lang='es')

            print(" >> Summary: ", self.forecast.currently.summary)
            print(" >> Icon: ", self.forecast.currently.icon)
            print(" >> Temperature: ", self.forecast.currently.temperature)
            print(" >> Humidity: ", self.forecast.currently.humidity)
            print(" >> Wind Speed: ", self.forecast.currently.wind_speed)
            print(" >> Pressure: ", self.forecast.currently.pressure)

            print(' >> Current summary: ' + self.forecast.currently.summary)
            #print(' >> Minutely summary: ' + self.forecast.minutely.summary)
            print(' >> Hourly summary: ' + self.forecast.hourly.summary)

            print("Get icon index:")
            weather_icons = {
                "clear-day": "01",
                "clear-night": "02",
                "partly-cloudy-day": "03",
                "partly-cloudy-night": "04",
                "cloudy": "05",
                "fog": "06",
                "wind": "07",
                "sleet": "08",
                "rain": "09",
                "snow": "10",
            }
            weather_icon_index = weather_icons.get(
                self.forecast.currently.icon)
            print(" >> Icon index: ", weather_icon_index)

            command = 'W' + weather_icon_index + '\r'
            print("Weather command: ", command)
            self.comport.write(bytes(command, 'UTF-8'))
        except:
            print("Exception occured during weather update")
Ejemplo n.º 17
0
class darksky(object): 
    def __init__(self): 

        self.conn = sqlite3.connect('project.db')
        c = self.conn.cursor()
        c.execute('''CREATE TABLE IF NOT EXISTS city_hourly (city_name text, hourly text)''')
        c.execute('''CREATE TABLE IF NOT EXISTS city_daily (city_name text, daily text)''')
        self.conn.commit()
        #darksky secret key
        secret_key = 'c59726c51f4df85958f9b9843e2c55c8'
        self.darksky = DarkSky(secret_key)

    def newpoint(self):
        return random.uniform(-180,180), random.uniform(-90, 90)


    def cities(self):
        points = (self.newpoint() for x in range(10))
        for point in points:
            longitude = point[0]
            latitude = point[1]
            forecast = self.darksky.get_forecast(
            latitude, longitude,
            extend=False, # default `False`
            lang=languages.ENGLISH, # default `ENGLISH`
            units=units.AUTO, # default `auto`
            exclude=[weather.MINUTELY, weather.ALERTS], # default `[]`,
            timezone='UTC' # default None - will be set by DarkSky API automatically
            )       
            current_city_forecast = forecast.hourly.data[0].humidity
            current_city_forecasts = forecast.daily.data[0].humidity
            c = self.conn.cursor()
            c.execute ('SELECT * FROM city_hourly WHERE city_name = ? AND hourly = ?', (str(point[0]) + "," + str(point[1]),current_city_forecast,))
            if c.fetchone() is None: 
                    c.execute('INSERT INTO city_hourly VALUES (?,?)', (str(point[0]) + "," + str(point[1]),current_city_forecast,))
                    self.conn.commit()
            c.execute ('SELECT * FROM city_daily WHERE city_name = ? AND daily = ?', (str(point[0]) + "," + str(point[1]),current_city_forecasts,))
            if c.fetchone() is None: 
                    c.execute('INSERT INTO city_daily VALUES (?,?)', (str(point[0]) + "," + str(point[1]),current_city_forecasts,))
                    self.conn.commit()
Ejemplo n.º 18
0
    def getweather(self):
        api_key = os.environ['DARKSKY_API_KEY']
        darksky = DarkSky(api_key)
        coordinates = self.getcoords()

        geodata = dict()
        geodata['lat'] = coordinates['geometry']['location']['lat']
        geodata['lng'] = coordinates['geometry']['location']['lng']

        latitude = geodata['lat']
        longitude = geodata['lng']
        forecast = darksky.get_forecast(
            latitude,
            longitude,
            extend=False,  # default `False`
            lang=languages.ENGLISH,  # default `ENGLISH`
            values_units=units.AUTO,  # default `auto`
            exclude=[],  # default `[]`,
            timezone=
            None  # default None - will be set by DarkSky API automatically
        )
        return forecast
Ejemplo n.º 19
0
def result():
    if request.method == 'POST':
        result = request.form
        print(result['mlocation'])
        geolocator = Nominatim(user_agent="MJGEo")
        location = geolocator.geocode(result['mlocation'])
        mloc = location
        API_KEY = 'e2fea81b36c2588f1315c4ad2b721989'
        darksky = DarkSky(API_KEY)
        latitude = location.latitude
        longitude = location.longitude
        forecast = darksky.get_forecast(
            latitude,
            longitude,
            extend=False,  # default `False`
            lang=languages.ENGLISH,  # default `ENGLISH`
            units=units.AUTO,  # default `auto`
            exclude=[weather.MINUTELY, weather.ALERTS]  # default `[]`
        )

        summary = forecast.hourly.summary
        temperature = forecast.hourly.data[0].temperature
        icon = forecast.daily.data[0].icon
        visibility = forecast.daily.data[0].visibility
        print(temperature)
        print(forecast.timezone)
        forecast.latitude  # 42.3601
        forecast.longitude  # -71.0589
        forecast.timezone  # timezone for coordinates. For exmaple: `America/New_York`

        forecast.currently  # CurrentlyForecast. Can be finded at darksky/forecast.py
        forecast.minutely  # MinutelyForecast. Can be finded at darksky/forecast.py
        forecast.hourly  # HourlyForecast. Can be finded at darksky/forecast.py
        forecast.daily  # DailyForecast. Can be finded at darksky/forecast.py
        forecast.alerts  # [Alert]. Can be finded at darksky/forecast.py
        params = [mloc, summary, temperature, icon, visibility]
        return render_template("index.html", params=params)
Ejemplo n.º 20
0
    def extract_data(self, message):
        try:
            responseDark = requests.get(
                "https://api.darksky.net/forecast/68a391b503f11aa6fa13d405bfefdaba/10,-10"
            )
            darksky = DarkSky("68a391b503f11aa6fa13d405bfefdaba")
            latitude = message['latitude']
            longitude = message['longitude']

            forecast = darksky.get_forecast(
                latitude,
                longitude,
                extend=False,
                lang=languages.ENGLISH,
                values_units=units.AUTO,
                exclude=[weather.MINUTELY, weather.ALERTS],
                timezone='UTC')
            current = forecast.currently
            mssg = {
                'summary': current.summary,
                'windSpeed': current.wind_speed,
                'humidity': current.humidity,
                'temperature': current.temperature
            }
            return mssg

        except Exception as e:
            print(e)
            mssg = {
                'summary': 'overcast',
                'windSpeed': 12,
                'humidity': 78,
                'temperature': 42
            }
            print(mssg)
            return mssg
Ejemplo n.º 21
0
class WeatherSummary(Screen):
    """Screen to show weather summary for a selected location."""
    location_label = StringProperty("")

    def __init__(self, api_key, location, **kwargs):
        super(WeatherSummary, self).__init__(**kwargs)
        self._location = location
        # self._key = api_key
        self.location_label = self.name
        self._darksky = DarkSky(api_key)
        self._forecast = None
        self._hourly = None
        self.bx_forecast = self.ids.bx_forecast
        self.bx_hourly = self.ids.bx_hourly
        self.nextupdate = 0
        self.timer = None

    def on_enter(self):
        # Check if the next update is due
        if (time.time() > self.nextupdate):
            dt = 0.5
        else:
            dt = self.nextupdate - time.time()

        self.timer = Clock.schedule_once(self.getData, dt)

    def on_leave(self):
        Clock.unschedule(self.timer)

    def getData(self, *args):
        # Get the forecast
        self._forecast = self._darksky.get_forecast(
            float(self._location[0]),
            float(self._location[1]),
            extend=False,  # default `False`
            lang=languages.ENGLISH,  # default `ENGLISH`
            units=units.AUTO,  # default `auto`
            exclude=[weather.MINUTELY, weather.ALERTS],  # default `[]`,
            # timezone='UTC'  # default None - will be set by DarkSky API automatically
        )

        # Clear the screen of existing overlays
        self.bx_forecast.clear_widgets()
        self.bx_hourly.clear_widgets()

        # If we've got daily info then we can display it.
        if self._forecast.daily:
            for day in self._forecast.daily.data[:4]:
                frc = WeatherForecastDay(daily_forecast_item=day)
                self.bx_forecast.add_widget(frc)

        # If not, let the user know.
        else:
            error_label = Label(text="Error getting weather data.")
            self.bx_forecast.add_widget(error_label)

        # If we've got hourly weather data then show it
        if self._forecast.hourly:

            # We need a scroll view as there's a lot of data...
            w = len(self._forecast.hourly.data) * 130
            bx = BoxLayout(orientation="horizontal",
                           size=(w, 180),
                           size_hint=(None, None),
                           spacing=5)
            sv = ScrollView(size_hint=(1, 1))
            sv.add_widget(bx)

            for hour in self._forecast.hourly.data:
                frc = WeatherForecastHourly(hourly_forecast_item=hour)
                bx.add_widget(frc)
            self.bx_hourly.add_widget(sv)

        # If there's no data, let the user know
        else:
            error_label = Label(text="Error getting weather data.")
            self.bx_forecast.add_widget(error_label)

        # We're done, so schedule the next update
        if self._forecast.hourly and self._forecast.daily:
            dt = 60 * 60
        else:
            dt = 5 * 60

        self.nextupdate = time.time() + dt
        self.timer = Clock.schedule_once(self.getData, dt)
Ejemplo n.º 22
0
class DarkSkyApiHelper(object):
    def __init__(self, latitude=None, longitude=None, sampleRange=None):

        jsonObj = self.__get_config()
        apiKey = self.__get_api_secret(jsonObj)

        self.longitude = longitude or self.__get_longitude(jsonObj)
        self.latitude = latitude or self.__get_latitude(jsonObj)
        self.sampleRange = sampleRange or self.__get_sample_forecast_range(
            jsonObj)
        self.client = DarkSky(apiKey)

    def __str__(self):

        return dumps(str(self.__dict__))

    def __get_config(self):

        jsonFile = open(CONFIGURATION_PATH, "r")
        jsonObj = load(jsonFile)
        jsonFile.close()

        return jsonObj

    def __get_api_secret(self, jsonObj):

        apiKey = jsonObj["api_key"]

        return apiKey

    def __get_latitude(self, jsonObj):

        lat = jsonObj["latitude"]

        return lat

    def __get_longitude(self, jsonObj):

        lon = jsonObj["longitude"]

        return lon

    def __get_sample_forecast_range(self, jsonObj):

        sampleRange = jsonObj["sample_forecast_range_hours"]

        return sampleRange

    def get_weather_forecast(self):

        forecast = self.client.get_forecast(self.latitude, self.longitude)

        return forecast

    def get_pct_chance_of_rain(self):

        forecast = self.get_weather_forecast()

        now = datetime.now()
        hour = now.hour
        date = now.date()

        hourlyData = forecast.hourly.data
        hourlyPctRain = [
            x.precip_probability for x in hourlyData
            if (hour + self.sampleRange) > x.time.hour >= hour
            and x.time.date() == date
        ]
        pRain = mean(hourlyPctRain)

        return pRain
Ejemplo n.º 23
0
with open("knowledge.JSON") as file:
	robot_brain = json.load(file)

# get current time by timezone
tz_Hanoi = pytz.timezone('Asia/Ho_Chi_Minh') # timezone
datetime_Hanoi = datetime.now(tz_Hanoi) # current time

# darksky - daily weather
API_KEY = 'e2fea81b36c2588f1315c4ad2b721989' # This is OneMonth's api key (OneMonth.com)

darksky = DarkSky(API_KEY)

forecast = darksky.get_forecast( # get forecast for Hanoi
    21.0294498, # latitude
    105.8544441, # longitude 
    extend=False, # default `False`
    lang=languages.ENGLISH, # default `ENGLISH`
    # units=units.AUTO, # default `auto`
    exclude=[weather.MINUTELY, weather.ALERTS] # default `[]`
)


# 2.Define fundamental function
def getRequest(ask): # record user's voice
	with sr.Microphone() as mic:
		print(ask)
		audio = speech.listen(mic)

	try:
		return speech.recognize_google(audio)
	except: # google can't recognize the content of the audio
		return "" 
Ejemplo n.º 24
0
from darksky.api import DarkSky
from darksky.types import languages, units, weather

API_KEY = 'e2fea81b36c2588f1315c4ad2b721989'

darksky = DarkSky(API_KEY)

latitude = 42.3601
longitude = -71.0589
forecast = darksky.get_forecast(
    latitude,
    longitude,
    extend=False,  # default `False`
    lang=languages.ENGLISH,  # default `ENGLISH`
    units=units.AUTO,  # default `auto`
    exclude=[weather.MINUTELY, weather.ALERTS]  # default `[]`
)

print(forecast.currently.temperature)

forecast.latitude  # 42.3601
forecast.longitude  # -71.0589
forecast.timezone  # timezone for coordinates. For exmaple: `America/New_York`

forecast.currently  # CurrentlyForecast. Can be finded at darksky/forecast.py
forecast.minutely  # MinutelyForecast. Can be finded at darksky/forecast.py
forecast.hourly  # HourlyForecast. Can be finded at darksky/forecast.py
forecast.daily  # DailyForecast. Can be finded at darksky/forecast.py
forecast.alerts  # [Alert]. Can be finded at darksky/forecast.py
Ejemplo n.º 25
0
def do_update():
    API_KEY = open("darksky-secret").readline().rstrip()
    darksky = DarkSky(API_KEY)
    lat, lon = 42.417821, -71.177747

    forecast = darksky.get_forecast(lat,
                                    lon,
                                    exclude=[weather.MINUTELY, weather.ALERTS])
    print("got forecast from darksky")
    now = forecast.currently
    today = forecast.daily.data[0]
    hourly = forecast.hourly.data

    temp_now = two_dig(now.apparent_temperature)

    if UNTIL_MIDNIGHT:
        rest_of_day = [x for x in hourly if x.time.day == datetime.now().day]
        temp_hi = two_dig(max([x.apparent_temperature for x in rest_of_day]))
        temp_low = two_dig(min([x.apparent_temperature for x in rest_of_day]))
        today_icon = worst([x.icon for x in rest_of_day])
    else:
        temp_hi = two_dig(today.apparent_temperature_high)
        temp_low = two_dig(today.apparent_temperature_low)
        today_icon = today.icon

    sleep(5)
    paper_cmd("wake")
    paper_cmd("clear")

    paper_bignum(temp_now[0], 20, 20)
    paper_bignum(temp_now[1], 160, 20)

    paper_smallnum(temp_hi[0], 310, 10)
    paper_smallnum(temp_hi[1], 390, 10)

    paper_smallnum(temp_low[0], 310, 175)
    paper_smallnum(temp_low[1], 390, 175)

    if now.icon == today_icon or FORECAST_ONLY:
        paper_image(icon(3, today_icon), 500, 160)
    else:
        paper_image(icon(3, now.icon), 500, 30)
        paper_image(icon(3, today_icon), 500, 290)

    paper_image("UV.BMP", 20, 470)
    paper_smallnum(uv_one_dig(today.uv_index), 80, 310)

    paper_fontsize(32)
    paper_text(today.summary, 20, 570)

    nowt = datetime.now()
    paper_text(nowt.strftime("Last update %H:%M"), 20, 1)
    paper_text(
        (nowt + timedelta(seconds=seconds_between_updates)
         ).strftime("Next update %H:%M"),
        550,
        1,
    )

    # day of week and date
    paper_fontsize(64)
    paper_text(nowt.strftime("%a"), 310, 370)
    paper_text(nowt.strftime("%b %-d"), 280, 440)
    paper_rect(260, 360, 455, 520)

    paper_cmd("update")
    paper_cmd("stop")
    paper_deepsleep(seconds_between_updates)
    print("done")
Ejemplo n.º 26
0
from darksky.api import DarkSky, DarkSkyAsync
from darksky.types import languages, units, weather


API_KEY = '0123456789abcdef9876543210fedcba'

# Synchronous way
darksky = DarkSky(API_KEY)

latitude = 42.3601
longitude = -71.0589
forecast = darksky.get_forecast(
    latitude, longitude,
    extend=False, # default `False`
    lang=languages.ENGLISH, # default `ENGLISH`
    values_units=units.AUTO, # default `auto`
    exclude=[weather.MINUTELY, weather.ALERTS], # default `[]`,
    timezone='UTC' # default None - will be set by DarkSky API automatically
)

# Synchronous way Time Machine 

from datetime import datetime as dt

darksky = DarkSky(API_KEY)
t = dt(2018, 5, 6, 12)

latitude = 42.3601
longitude = -71.0589
forecast = darksky.get_time_machine_forecast(
    latitude, longitude,
Ejemplo n.º 27
0
def get_forecast_sync() -> Forecast:
    darksky = DarkSky("api_key")

    return darksky.get_forecast(DATA["latitude"], DATA["longitude"])
Ejemplo n.º 28
0
# weather_thing.py

from darksky.api import DarkSky
import csv
import time
import os.path
import weather_plotter as plt

API_KEY = '117eeede0b36be4e9adee42396747ac7'

darksky = DarkSky(API_KEY)

latitude = 47.209660
longitude = -122.425690
fcst = darksky.get_forecast(latitude, longitude)

line = {
    'now_temp': fcst.currently.apparent_temperature,
    'now_icon': fcst.currently.icon,
    'fcst_temp': fcst.daily.data[0].temperature_high,
    'fcst_icon': fcst.daily.data[0].icon,
    'year': time.strftime('%Y'),
    'month': time.strftime('%m'),
    'day': time.strftime('%d'),
    'hour': time.strftime('%H'),
    'minute': time.strftime('%M'),
    'second': time.strftime('%S'),
    'now_humi': fcst.currently.humidity
}

file_name = 'data_weather_thing.csv'
Ejemplo n.º 29
0
def get_forecast_sync() -> Forecast:
    darksky = DarkSky('api_key')

    return darksky.get_forecast(DATA['latitude'], DATA['longitude'])
Ejemplo n.º 30
0
Tashkent_city = Cities(4, 'Tashkent', 41.299496, 69.240074)
Sydney_city = Cities(5, 'Sydney', -33.868820, 151.209290)

# Inserts all cities into the "cities" table
cities = [NewYork_city, London_city, Moscow_city, Tashkent_city, Sydney_city]
for i in range(len(cities)):
    insert_city(cities[i])

# Saves weather information into weather table for a specified cities, if data differs >=1 min
starttime = time.time()
while get_info_from_API:
    for i in range(len(cities)):
        city_weather = darksky.get_forecast(cities[i].lat,
                                            cities[i].lon,
                                            extend=False,
                                            lang=languages.ENGLISH,
                                            units=units.AUTO,
                                            exclude=[],
                                            timezone=None)
        #city_weather_copy = copy.deepcopy(city_weather)
        c.execute(
            """SELECT * FROM weather WHERE city_id=:city_id ORDER BY time DESC LIMIT 1""",
            {'city_id': i + 1})

        selected_data = c.fetchall()
        current_weather = Weather_info.get_weather_info_tuple(city_weather)
        if selected_data == []:
            insert_weather(city_weather, i + 1)
            print(
                "Current weather information of {} was saved first time into weather table ..."
                .format(city_weather.timezone))