Ejemplo n.º 1
0
def is_at_night(mo=None):
    try:
        a = Location()
        a.timezone = settings.TIME_ZONE
        tz = pytz.timezone(a.timezone)
        #Tue, 22 Jul 2008 08:17:41 +0200
        #Sun, 26 Jan 2014 17:39:49 +01:00
        a_sunset = a.sunset()

        a_sunrise = a.sunrise()

        n = datetime.datetime.now()
        n = tz.localize(n)
        logger.debug("NOW: %s; sunrise: %s; dif: %s"  % (n, a_sunrise, n - a_sunrise))
        logger.debug("NOW: %s; sunset: %s; dif: %s" % (n, a_sunset, n - a_sunset))
        passed_sunrise = (n - a_sunrise) > datetime.timedelta(minutes=settings.MINUTES_AFTER_SUNRISE_FOR_DAY)
        logger.debug("Passed %s sunrise more than %s minutes" % (passed_sunrise, settings.MINUTES_AFTER_SUNRISE_FOR_DAY))
        passed_sunset = (n - a_sunset) > datetime.timedelta(minutes=settings.MINUTES_AFTER_SUNSET_FOR_DAY)
        logger.debug("Passed %s sunset more than %s minutes" % (passed_sunset, settings.MINUTES_AFTER_SUNSET_FOR_DAY))

        if not passed_sunrise or passed_sunset:
            logger.debug("Is at night")
            return 1
        if passed_sunrise and not passed_sunset:
            logger.debug("Is not at night")
            return 0
    except Exception as ex:
        logger.error(ex)
Ejemplo n.º 2
0
    def compute(self):
        location = Location(('name', 'reg', self.lat, self.lon, 'Europe/Moscow', self.alt))

        # 15' sun bottom + 35' refraction
        alt = location.solar_elevation()
        daytime = 'day'
        daytime_ext = 'day'
        if -6 <= alt < -5. / 6:
            daytime = 'twilight'
            daytime_ext = 'civil_twilight'
        elif -12 <= alt < -6:
            daytime = 'night'
            daytime_ext = 'nautical_twilight'
        elif -18 <= alt < -12:
            daytime = 'night'
            daytime_ext = 'astro_twilight'
        elif alt < -18:
            daytime = 'night'
            daytime_ext = 'night'

        self.context.set_item_value('daytime', daytime)
        self.context.set_item_value('daytime_ext', daytime_ext)
        self.context.set_item_value('sun_alt', alt)
        self.context.set_item_value('sun_az', location.solar_azimuth())

        sun = location.sun()
        self.context.set_item_value('sunrise', sun['sunrise'])
        self.context.set_item_value('sunset', sun['sunset'])
        self.context.set_item_value('noon', sun['noon'])

        self.context.set_item_value('moon_phase', location.moon_phase())
	def getSunTimes(self):
		a = Location()
		a.timezone = "Europe/Berlin"
		tz = pytz.timezone(a.timezone)
		sunData = a.sun()
		n = datetime.datetime.now()
		n = tz.localize(n)
Ejemplo n.º 4
0
 def doAction(self,r,sr,words,sensorList):
     if self.tz == None:
         os.system("espeak -s 120 'loading solar data'")
         self.tz = tzwhere.tzwhere()
     fix = sensorList["location"].getLastData()
     if fix["lastFix"] == None:
         return "I don't know where you are"
     l = Location()
     l.name = 'gpsFix'
     l.region = 'gpsFix'
     l.latitude = float(fix["lastFix"]["lat"])
     l.longitude = float(fix["lastFix"]["lon"])
     l.timezone = self.tz.tzNameAt(float(fix["lastFix"]["lat"]),float(fix["lastFix"]["lon"]))
     l.elevation = float(fix["lastFix"]["alt"])
     if "sunset" in words:
         return str(l.sunset().strftime("%-I:%M%P"))
     if "sunrise" in words:
         return str(l.sunrise().strftime("%-I:%M%P"))
     if "phase of the moon" in words:
         return str(l.moon_phase())
Ejemplo n.º 5
0
def setup(hass, config):
    """ Tracks the state of the sun. """
    if None in (hass.config.latitude, hass.config.longitude):
        _LOGGER.error("Latitude or longitude not set in Home Assistant config")
        return False

    latitude = util.convert(hass.config.latitude, float)
    longitude = util.convert(hass.config.longitude, float)
    errors = []

    if latitude is None:
        errors.append('Latitude needs to be a decimal value')
    elif -90 > latitude < 90:
        errors.append('Latitude needs to be -90 .. 90')

    if longitude is None:
        errors.append('Longitude needs to be a decimal value')
    elif -180 > longitude < 180:
        errors.append('Longitude needs to be -180 .. 180')

    if errors:
        _LOGGER.error('Invalid configuration received: %s', ", ".join(errors))
        return False

    platform_config = config.get(DOMAIN, {})

    elevation = platform_config.get(CONF_ELEVATION)

    from astral import Location, GoogleGeocoder

    location = Location(
        ('', '', latitude, longitude, hass.config.time_zone, elevation or 0))

    if elevation is None:
        google = GoogleGeocoder()
        try:
            google._get_elevation(location)  # pylint: disable=protected-access
            _LOGGER.info('Retrieved elevation from Google: %s',
                         location.elevation)
        except urllib.error.URLError:
            # If no internet connection available etc.
            pass

    sun = Sun(hass, location)
    sun.point_in_time_listener(dt_util.utcnow())

    return True
Ejemplo n.º 6
0
def calc_sunset_times(stops_df, latitude, longitude, timezone, date_col = 'date'):
    """
    Calculates the sunset times for all unique dates in stops_df using the provided latitude and longitude using the given
    timezone.

    INPUTS
    =======
    stops_df: A pandas DataFrame that contains stops observations.
    latitude: An object that can be converted to a float that represents the latitude
    longitude: An object that can be converted to a float that represents the longitude
    timezone: A string indicating the timezone to calculate the times in.
              For a list of accepted arguments for timezone, use the follow code:

              from pytz import all_timezones
              for timezone in all_timezones:
                  print(timezone)
    date_col: A string indicating the date column on stops_df. By default assumes it is 'date'.

    RETURNS
    ========
    A pandas DataFrame in which each row contains information about a date, with column 'sunset' representing sunset
    time, 'dusk' representing dusk time, 'sunset_minutes' representing sunset time in minutes, and 'dusk_minutes' representing
    dusk time in minutes.
    """
    l = Location()
    l.solar_depression = 'civil'
    l.latitude = float(latitude)
    l.longitude = float(longitude)
    l.timezone = timezone
    l.elevation = 0
    unique_dates = list(stops_df[date_col].unique())
    sunset = [l.sun(pd.Timestamp(date), local = True)['sunset'].time() for date in unique_dates]
    dusk = [l.sun(pd.Timestamp(date), local = True)['dusk'].time() for date in unique_dates]
    sunset_minutes = [time.hour * 60 + time.minute for time in sunset]
    dusk_minutes = [time.hour * 60 + time.minute for time in dusk]
    sunset_times = pd.DataFrame(zip(unique_dates, sunset, dusk, sunset_minutes, dusk_minutes))
    sunset_times.columns = ['date', 'sunset', 'dusk', 'sunset_minute', 'dusk_minute']
    return sunset_times
Ejemplo n.º 7
0
    def checkLights(self):
        # Get sunrise and sunset for Woodinville, WA
        l = Location()
        l.latitude =  47.763212
        l.longitude =  -122.068400
        l.timezone = 'US/Pacific'

        sunrise = l.sun()['dawn']
        sunrise = sunrise.replace(tzinfo=None)
        sunrise_hour = sunrise.strftime('%H')
        sunrise_minute = sunrise.strftime('%M')
        self.log.writeln('sunrise {}:{}'.format(sunrise_hour, sunrise_minute))

        sunset = l.sun()['sunset']
        sunset = sunset.replace(tzinfo=None)
        sunset_hour = sunset.strftime('%H')
        sunset_minute = sunset.strftime('%M')
        self.log.writeln('sunset {}:{}'.format(sunset_hour, sunset_minute))

        current_time = datetime.now()
        current_hour = current_time.hour
        current_minute = current_time.minute

        self.log.writeln('current time={}:{}'.format(current_hour, current_minute))

        sunrise_delta = sunrise - current_time
        sunrise_seconds = sunrise_delta.total_seconds()
        self.log.writeln('time till sunrise is {} seconds'.format(sunrise_seconds))

        sunset_delta = sunset - current_time
        sunset_seconds = sunset_delta.total_seconds()
        self.log.writeln('time till sunset is {} seconds'.format(sunset_seconds))

        if sunrise_seconds < 0 and sunset_seconds <= 0:
            self.log.writeln("Turning on the lights")
            self.turnOn()
            self.log.writeln("Turning off the lights in {} seconds".format(-sunrise_seconds))
            return -sunrise_seconds
        elif sunrise_seconds > 0 and sunset_seconds > 0:
            self.log.writeln("Turning on the lights")
            self.turnOn()
            self.log.writeln("Turning off the lights in {} seconds".format(sunrise_seconds))
            return sunrise_seconds
        elif sunrise_seconds <= 0 and sunset_seconds > 0:
            self.log.writeln("Turning off the lights")
            self.turnOff()
            self.log.writeln("Turning on the lights in {} seconds".format(sunset_seconds))
            return sunset_seconds
Ejemplo n.º 8
0
def get_astral_location(opp: OpenPeerPowerType) -> "astral.Location":
    """Get an astral location for the current Open Peer Power configuration."""
    from astral import Location

    latitude = opp.config.latitude
    longitude = opp.config.longitude
    timezone = str(opp.config.time_zone)
    elevation = opp.config.elevation
    info = ("", "", latitude, longitude, timezone, elevation)

    # Cache astral locations so they aren't recreated with the same args
    if DATA_LOCATION_CACHE not in opp.data:
        opp.data[DATA_LOCATION_CACHE] = {}

    if info not in opp.data[DATA_LOCATION_CACHE]:
        opp.data[DATA_LOCATION_CACHE][info] = Location(info)

    return opp.data[DATA_LOCATION_CACHE][info]
Ejemplo n.º 9
0
def get_astral_location(hass: HomeAssistantType) -> 'astral.Location':
    """Get an astral location for the current Home Assistant configuration."""
    from astral import Location

    latitude = hass.config.latitude
    longitude = hass.config.longitude
    timezone = str(hass.config.time_zone)
    elevation = hass.config.elevation
    info = ('', '', latitude, longitude, timezone, elevation)

    # Cache astral locations so they aren't recreated with the same args
    if DATA_LOCATION_CACHE not in hass.data:
        hass.data[DATA_LOCATION_CACHE] = {}

    if info not in hass.data[DATA_LOCATION_CACHE]:
        hass.data[DATA_LOCATION_CACHE][info] = Location(info)

    return hass.data[DATA_LOCATION_CACHE][info]
Ejemplo n.º 10
0
def get_astral_location(hass: HomeAssistant) -> astral.Location:
    """Get an astral location for the current Home Assistant configuration."""
    from astral import Location  # pylint: disable=import-outside-toplevel

    latitude = hass.config.latitude
    longitude = hass.config.longitude
    timezone = str(hass.config.time_zone)
    elevation = hass.config.elevation
    info = ("", "", latitude, longitude, timezone, elevation)

    # Cache astral locations so they aren't recreated with the same args
    if DATA_LOCATION_CACHE not in hass.data:
        hass.data[DATA_LOCATION_CACHE] = {}

    if info not in hass.data[DATA_LOCATION_CACHE]:
        hass.data[DATA_LOCATION_CACHE][info] = Location(info)

    return hass.data[DATA_LOCATION_CACHE][info]
Ejemplo n.º 11
0
def get_location(location_config):
    ''' return an Astral location object based on the configured location '''
    LOCATION_CONFIG_SCHEMA.validate(location_config)

    if type(location_config) == str:
        # This should be a string that Astral recognizes out of the box
        return Astral()[location_config]
    else:
        location = Location()
        location.latitude = location_config['latitude']
        location.longitude = location_config['longitude']
        location.timezone = location_config['timezone']
        location.elevation = location_config['elevation']
        return location
Ejemplo n.º 12
0
def setup(hass, config):
    """Track the state of the sun."""
    if None in (hass.config.latitude, hass.config.longitude):
        _LOGGER.error("Latitude or longitude not set in Home Assistant config")
        return False

    latitude = util.convert(hass.config.latitude, float)
    longitude = util.convert(hass.config.longitude, float)
    errors = []

    if latitude is None:
        errors.append('Latitude needs to be a decimal value')
    elif -90 > latitude < 90:
        errors.append('Latitude needs to be -90 .. 90')

    if longitude is None:
        errors.append('Longitude needs to be a decimal value')
    elif -180 > longitude < 180:
        errors.append('Longitude needs to be -180 .. 180')

    if errors:
        _LOGGER.error('Invalid configuration received: %s', ", ".join(errors))
        return False

    platform_config = config.get(DOMAIN, {})

    elevation = platform_config.get(CONF_ELEVATION)
    if elevation is None:
        elevation = location_util.elevation(latitude, longitude)

    from astral import Location

    location = Location(('', '', latitude, longitude,
                         hass.config.time_zone.zone, elevation))

    sun = Sun(hass, location)
    sun.point_in_time_listener(dt_util.utcnow())

    return True
Ejemplo n.º 13
0
def getSunUPandSunDown(when=datetime.now()):

    # geolocate dawn and sunset
    try:
        g = geocoder.ip('me')
        logger.log(logging.DEBUG - 3,
                   'Geolocation found = ' + pp.pformat(g.lat))
        logger.log(
            logging.DEBUG - 3,
            'Geolocation found : lat=' + str(g.lat) + ' lng=' + str(g.lng))
        l = Location()
        l.latitude = g.lat
        l.longitude = g.lng
        l.timezone = 'US/Eastern'
        dawn = l.sun(when)['dawn'].replace(tzinfo=None)
        sunset = l.sun(when)['sunset'].replace(tzinfo=None)
        logger.log(logging.DEBUG - 3, 'Todays dawn = ' + pp.pformat(dawn))
        logger.log(logging.DEBUG - 3, 'Todays sunset = ' + pp.pformat(sunset))
        return dawn, sunset
    except:
        return None, None
Ejemplo n.º 14
0
def main():
    state = parse()
    if state.latitude is None or state.longitude is None:
        usageError(
            'Error: the following arguments are required: --latitude, --longitude'
        )

    location = Location()

    validateTimezone(state, location)
    validateDate(state, location)

    state.offset = timedelta(minutes=state.offset)

    location.latitude = state.latitude
    location.longitude = state.longitude
    location.elevation = state.elevation

    sun = location.sun()
    sunset = sun['sunset']
    sunrise = sun['sunrise']

    # Check if its currently day if possible
    day = isDay(state.date, sunrise, sunset,
                offset=state.offset) if state.date.tzinfo is not None else True

    if state.state:  # Show current state
        print('Day' if day else 'Night')

    if not state.time:  # Don't show relative times
        print(sunrise.strftime('Sunrise: %H:%M'))
        print(sunset.strftime('Sunset: %H:%M'))
    elif day:
        diff = sunset - state.date - state.offset
        if diff.total_seconds() < 0:
            diff += timedelta(minutes=24 * 60)
        print('Minutes till sunset: %02d' % (diff.total_seconds() // 60))
    else:
        diff = sunrise - state.date + state.offset
        if diff.total_seconds() < 0:
            diff += timedelta(minutes=24 * 60)
        print('Minutes till sunrise: %02d' % (diff.total_seconds() // 60))

    sys.exit(not day)
Ejemplo n.º 15
0
def test_Location_TimezoneLookup():
    c = Location()
    assert c.tz == pytz.timezone('Europe/London')
    c.timezone='Europe/Stockholm'
    assert c.tz == pytz.timezone('Europe/Stockholm')
Ejemplo n.º 16
0
def test_Location_TimezoneNameBad():
    c = Location()
    with raises(ValueError):
        c.timezone = 'bad/timezone'
Ejemplo n.º 17
0
def test_Location_TimezoneNameNoLocation():
    c = Location()
    c._timezone_group = 'Europe'
    c._timezone_location = ''
    assert c.timezone == 'Europe'
Ejemplo n.º 18
0
def test_Location_TimezoneName():
    c = Location()
    assert c.timezone == 'Europe/London'
    c.name = 'Asia/Riyadh'
    assert c.name == 'Asia/Riyadh'
Ejemplo n.º 19
0
def test_Location_Country():
    c = Location()
    assert c.region == 'England'
    c.region = 'Australia'
    assert c.region == 'Australia'
Ejemplo n.º 20
0
from crontab import CronTab
from datetime import datetime
from astral import Location

# Location info for sunrise and sun calculation
info=( 'Brno', 'Czech Republic', 49.241921, 16.566693, 'Europe/Prague', 278 )
l=Location(info)

# Calculate sunrise and sunset for current day
brno_today_sunrise=l.sunrise(datetime.today().date(), True)
brno_today_sunset=l.sunset(datetime.today().date(), True)

# Open crontab file
file_cron=CronTab(tabfile='crontab.txt')

# Find open and close job in crontab and update 
# sunrise and sunset with calculated time 
for job in file_cron:
    if 'open command to window' in job.comment:
        job.hour.on(brno_today_sunrise.hour)
        job.minute.on(brno_today_sunrise.minute)
    elif 'close command to window' in job.comment:
        job.hour.on(brno_today_sunset.hour)
        job.minute.on(brno_today_sunset.minute)

# Write changes to crontab file
file_cron.write()
Ejemplo n.º 21
0
def test_Location_DawnUTC():
    c = Location()
    c.dawn(local=False)
Ejemplo n.º 22
0
def test_Location_SunsetUTC():
    c = Location()
    c.sunset(local=False)
Ejemplo n.º 23
0
def test_LocationReprDefault():
    l = Location()
    assert l.__repr__(
    ) == 'Greenwich/England, tz=Europe/London, lat=51.17, lon=0.00'
Ejemplo n.º 24
0
def test_LocationReprFull():
    l = Location(('London', 'England', 51.68, -0.05, 'Europe/London', 3))
    assert l.__repr__(
    ) == 'London/England, tz=Europe/London, lat=51.68, lon=-0.05'
Ejemplo n.º 25
0
def test_Location_SunriseUTC():
    c = Location()
    c.sunrise(local=False)
Ejemplo n.º 26
0
def test_Location_TimezoneLookupBad():
    c = Location()
    c._timezone_group = 'bad'
    c._timezone_location = 'timezone'
    with raises(AstralError):
        c.tz
Ejemplo n.º 27
0
def test_Location_Moon():
    c=Location()
    c.moon_phase()
Ejemplo n.º 28
0
def test_Location_Dawn():
    c = Location()
    c.dawn()
Ejemplo n.º 29
0
def test_Location_TzError():
    with raises(AttributeError):
        c = Location()
        c.tz = 1
Ejemplo n.º 30
0
def test_Location_Sunrise():
    c = Location()
    c.sunrise()
Ejemplo n.º 31
0
#!/usr/bin/env python

import datetime
from astral import Astral, Location
import pytz

def dt2min(dt):
    return dt.hour * 60 + dt.minute

loc = Location(("Santa Clara", "California", 37.21, -121.58, "US/Pacific", 22))
loc.solar_depression = 'civil'
oneday = datetime.timedelta(days=1)
soy = datetime.date(2016, 1, 1)
for  i in (range(1, 366)):
    sun = loc.sun(date=soy, local=True)
    print("{{ 0x{0:X}, 0x{1:X} }},".format(dt2min(sun['sunrise']), dt2min(sun['sunset'])))
    soy = soy + oneday
Ejemplo n.º 32
0
def test_Location_Dusk():
    c = Location()
    c.dusk()
Ejemplo n.º 33
0
def test_Location_DuskUTC():
    c = Location()
    c.dusk(local=False)
Ejemplo n.º 34
0
def test_LocationReprNoRegion():
    l = Location(('London', None, 51.68, -0.05, 'Europe/London', 3))
    assert l.__repr__() == 'London, tz=Europe/London, lat=51.68, lon=-0.05'
Ejemplo n.º 35
0
def test_Location_Sunset():
    c = Location()
    c.sunset()
Ejemplo n.º 36
0
#input files:
weather_irradiation = 'input/weather/solarirradiation_twenthe.csv'
weather_timebaseDataset = 3600  #in seconds per interval

#Simulation:
#number of days to simulate and skipping of initial days. Simulation starts at Sunday January 1.
numDays = 5  # number of days
startDay = 180  # Initial day
numHouses = 30

#Select the geographic location. Refer to the Astral plugin to see available locations (or give a lon+lat)
# Use e.g. https://www.latlong.net/
from astral import Location

location = Location()
location.solar_depression = 'civil'
location.latitude = 52.239095
location.longitude = 6.857018
location.timezone = 'Europe/Amsterdam'
location.elevation = 0

#Select the devices in the neighbourhood

#Devices
#Scale overall consumption:
consumptionFactor = 1.0  #consumption was a bit too high

# Penetration of emerging technology in percentages
# all values must be between 0-100
# These indicate what percentage of the houses has a certain device
Ejemplo n.º 37
0
import datetime
import time
import os

from astral import Location

# Initialize a custom location for astral, as it doesn't necessarily include
# your current city of residence
l = Location()

# These two doesn't really matter
l.name = os.getenv('CITY', 'Trondheim')
l.region = os.getenv('REGION', 'Europe')

# But these are important
l.latitude = float(os.getenv('LATITUDE', '63.446827'))
l.longitude = float(os.getenv('LONGITUDE', '10.421906'))
l.timezone = os.getenv('TIMEZONE', 'Europe/Oslo')
l.elevation = float(os.getenv('ELEVATION', '0'))

daytime = -1
changed = False

while True:
    now = datetime.datetime.now()

    if now.hour < l.sun()['dawn'].hour and time != 3:
        # Night
        daytime = 3
        changed = True