Ejemplo n.º 1
0
	def getCorrectBackground(self):
		if self.Weather == None:
			return "day-sunny"
		
		city_name = 'London'
		a = Astral()
		a.solar_depression = 'civil'
		city = a[city_name]
		now = datetime.datetime.utcnow().replace(tzinfo=utc)
		sun = city.sun(date=datetime.datetime.now(), local=True)
		
		if now < sun['dawn']:
			#night
			return self.getNightBackground()
		elif now < sun['sunrise']:
			#sunrise
			return self.getSunSetRiseBackground()
		elif now < sun['sunset']:
			#day
			return self.getDayBackground()
		elif now < sun['dusk']:
			#sunset
			return self.getSunSetRiseBackground()
		else:
			#night
			return self.getNightBackground()
Ejemplo n.º 2
0
 def __init__(self):
     self.hardware = Hardware()
     a = Astral()
     a.solar_depression = 'civil'
     self.city = a['Kiev']
     self.rpc_server = RPCServer(self.hardware) 
     self.rpc_server.start()
Ejemplo n.º 3
0
    async def async_update(self):
        try:
            date_offset = date.today() + relativedelta(
                **{self._date_units: self._date_value})
            city_name = self._city
            a = Astral()
            a.solar_depression = 'civil'
            city = a[city_name]
            s2 = city.sun(date=date_offset, local=False)
            time_offset = relativedelta(**{self._time_units: self._time_value})

            relative_sunrise = (s2["sunrise"] + time_offset)
            relative_sunset = (s2["sunset"] + time_offset)
            diff = relative_sunset - relative_sunrise
            diff_hours = diff.seconds / 3600
            self.attrs[ATTR_CITY] = city.name
            self.attrs[ATTR_REGION] = city.region
            self.attrs[ATTR_TIMEZONE] = city.timezone
            self.attrs[ATTR_LAT] = city.latitude
            self.attrs[ATTR_LONG] = city.longitude
            self.attrs[ATTR_SUNRISE] = str(
                relative_sunrise.strftime('%H:%M:%S'))
            self.attrs[ATTR_SUNSET] = str(relative_sunset.strftime('%H:%M:%S'))
            self.attrs[ATTR_HOURS_IN_DAY] = diff_hours
            self._available = True
        except (ClientError, gidgethub.GitHubException):
            self._available = False
            _LOGGER.exception("Error calculating multisun data.")
Ejemplo n.º 4
0
def jobUpdateAstral():
    a = Astral()
    a.solar_depression = myDepression
    city = a[myCity]

    sun = city.sun(date=datetime.date(datetime.datetime.today().year,
                                      datetime.datetime.today().month,
                                      datetime.datetime.today().day),
                   local=True)
    duskh = str(sun['dusk'])[11:13]
    duskm = str(sun['dusk'])[14:16]
    dusk = duskh + ":" + duskm

    logging.debug("New %s dusk in %s is set to %s", myDepression, myCity, dusk)

    dawnh = str(sun['dawn'])[11:13]
    dawnm = str(sun['dawn'])[14:16]
    dawn = dawnh + ":" + dawnm

    logging.debug("New %s dawn in %s is set to %s", myDepression, myCity, dawn)

    for s in mySwitches:
        if s.Type == "Sun":
            s.Stop()
            s.timeOn = dusk
            s.timeOff = dawn
            logging.info(">>> Astral updated %s and %s", dusk, dawn)
            s.Start()
Ejemplo n.º 5
0
    def is_over_sunset() -> bool:
        astral = Astral()
        astral.solar_depression = 'civil'
        sun = astral['Bucharest'].sun(date=datetime.datetime.now(), local=True)
        currentTime = datetime.datetime.now(timezone(general.timezone)).time()

        return currentTime > sun['sunset'].time()
Ejemplo n.º 6
0
def get_daylight_details():
    """Get details of solar path/daylight hours at site for today (local)"""

    # Instantiating Astral object (for calculating position of sun and moon)
    a = Astral()
    a.solar_depression = 'civil'

    # Instantiating an Astral location (hard-coded here since dealing with one site only, but
    # easily scalable if site required login and site lat and long were tied to user profile)
    l = Location()
    l.latitude = 37.8195
    l.longitude = -122.2523
    l.timezone = 'US/Pacific'
    l.elevation = 125

    sunrise = l.sunrise().strftime('%-I:%M%p')
    sunset = l.sunset().strftime('%-I:%M%p')
    day_length = str(l.sunset() - l.sunrise())
    solar_noon = l.solar_noon().strftime('%-I:%M%p')
    solar_zenith = l.solar_elevation(l.solar_noon().replace(tzinfo=None))
    solar_elevation = l.solar_elevation()

    daylight_data = {
        'sunrise': sunrise,
        'sunset': sunset,
        'daylength': day_length,
        'solar_noon': solar_noon,
        'zenith': solar_zenith,
        'elevation': solar_elevation
    }

    return jsonify(daylight_data)
Ejemplo n.º 7
0
def darkness_comes():
    '''
    return true if the sun has set in Columbus
    '''

    if ALWAYS_DARK:
        return True

    city_name = 'Columbus'
    a = Astral()
    a.solar_depression = 'civil'
    city = a[city_name]
    timezone = city.timezone

    sun_today = city.sun(date=datetime.datetime.now(), local=True)
    sunrise_today = sun_today['sunrise']
    sunset_today = sun_today['sunset']

    sun_tomorrow = city.sun(date=datetime.datetime.today() + datetime.timedelta(days=1), local=True)
    sunrise_tomorrow = sun_tomorrow['sunrise']
    sunset_tomorrow = sun_tomorrow['sunset']

    current_time = datetime.datetime.now(pytz.timezone('America/New_York'))

    # dark means it's earlier than sunrise or later than sunset
    if (current_time < sunrise_today) or (current_time > sunset_today and current_time < sunrise_tomorrow):
        # sun is down!
        return True
    else:
        # sun is up!
        return False
Ejemplo n.º 8
0
def get_astral_data(for_datetime):
    '''
    Returns the sunrise and sunset times for the given date.
    Uses the Astral package to compute sunrise/sunset for the
    configured city.
    Reference https://pythonhosted.org/astral/module.html
    :param for_datetime:
    :return: Returns a dict containing the keys sunrise and sunset.
    The values are datetime objects.
    '''
    a = Astral()
    a.solar_depression = "civil"
    # We use a city just to get a city object. Then we override the lat/long.
    # The city object can produce sunrise/sunset in local time.
    if Configuration.City() != "":
        city = a[Configuration.City()]
    else:
        # Default if no city is configured
        city = a["New York"]
    if Configuration.Latitude() != "":
        city.latitude = float(Configuration.Latitude())
    if Configuration.Longitude() != "":
        city.longitude = float(Configuration.Longitude())

    return city.sun(date=for_datetime, local=True)
Ejemplo n.º 9
0
def get_astral_data(for_datetime):
    '''
    Returns the sunrise and sunset times for the given date.
    Uses the Astral package to compute sunrise/sunset for the
    configured city.
    Reference https://pythonhosted.org/astral/module.html
    :param for_datetime:
    :return: Returns a dict containing the keys sunrise and sunset.
    The values are datetime objects.
    '''
    a = Astral()
    a.solar_depression = "civil"
    # We use a city just to get a city object. Then we override the lat/long.
    # The city object can produce sunrise/sunset in local time.
    if Configuration.City() != "":
        city = a[Configuration.City()]
    else:
        # Default if no city is configured
        city = a["New York"]
    if Configuration.Latitude() != "":
        city.latitude = float(Configuration.Latitude())
    if Configuration.Longitude() != "":
        city.longitude = float(Configuration.Longitude())

    return city.sun(date=for_datetime, local=True)
Ejemplo n.º 10
0
def ics():
    astral = Astral()
    astral.solar_depression = "civil"
    astral.depression = 6.0

    city = astral["Toronto"]

    cal = Calendar()
    cal.add("prodid", "-//Time of Day//time-of-day.herokuapp.com//")
    cal.add("version", "2.0")

    today = datetime.date.today()

    for x in range(-7, 8):
        date = today + datetime.timedelta(days=x)

        sun = city.sun(date=date, local=True)

        for summary, time in sun.items():
            event = Event()
            event.add("summary", summary.capitalize())
            event.add("dtstart", time)
            event.add("dtend", time)
            event.add("dtstamp", time)

            cal.add_component(event)

    resp = make_response(cal.to_ical())

    resp.headers["Content-Disposition"] = "attachment; filename=time-of-day.ics"
    resp.headers["Content-Type"] = "text/calendar"

    return resp
Ejemplo n.º 11
0
 def initialize(self):
     self.city_name = 'Sofia'
     a = Astral()
     a.solar_depression = 'civil'
     self.city = a[self.city_name]
     self.timezone = self.city.timezone
     self.sun_info = self.city.sun(date=date.today(), local=True)
Ejemplo n.º 12
0
def calc_sunlight() -> int:
    """
    Calculate an appropriate brightness for the bulb depending on
    current sunlight.
    :return: White brightness
    """
    a = Astral()
    a.solar_depression = 'civil'
    city = a[settings.LOCATION]
    sun = city.sun(date=datetime.now(), local=True)
    dt = datetime.now(sun['sunrise'].tzinfo)
    if dt.hour < 4 or dt.hour >= 22:
        return {'red': 255}
    elif dt < sun['sunrise']:
        return {
            'white':
            255 - (sun['sunrise'] - dt).total_seconds() / 3600 * 200 / 6
        }
    elif dt > sun['sunset']:
        return {
            'white':
            255 - (dt - sun['sunset']).total_seconds() / 3600 * 200 / 6
        }
    else:
        return {'white': 255}
Ejemplo n.º 13
0
def calculateSupply(nowTime, sampleTime, maxtime, numberOfHours, solarPower):
    # sample time is in minutes
    # returns an array of estimated energy units for each time sample
    # starting at nowTime
    maxTime = maxtime
    # return [0 for i in range(0, maxTime)]
    #############################
    astral = Astral()
    astral.solar_depression = 'civil'
    city = astral['Salt Lake City']
    # array of sky clear length maxTime, 1.0 is totally clear, 0 is cloudy
    clearSky = getSkyClear(nowTime, numberOfHours, sampleTime)
    # print "clear"
    # print clearSky
    sunStrength = getSunStrength(city, nowTime, numberOfHours, sampleTime)
    # print "sun Strength"
    print(len(sunStrength))
    onePower = [
        sunEstimate(sunStrength[i], clearSky[i]) * solarPower
        for i in range(0, maxTime)
    ]
    # print "one Power"
    # print onePower
    # supply = [calculateOneTimeEnergy(onePower[i], sampleTime, energySample) for i in range(0, maxTime)]
    # print supply
    return onePower
Ejemplo n.º 14
0
def getSolarInfo():
    a = Astral()
    a.solar_depression = 'civil'
    city = a['Seattle']
    timezone = city.timezone
    sun = city.sun(date=datetime.datetime.now())

    return sun
Ejemplo n.º 15
0
def get_sundown(target_date):
    a = Astral()
    a.solar_depression = 'civil'
    locale = a[city]
    sun = locale.sun(date=datetime.date(target_date.year, target_date.month,
                                        target_date.day),
                     local=True)
    return sun['sunset']
Ejemplo n.º 16
0
def graph_values(diff_array):
    graph_data = []
    graph_dates = []
    sum_value = 0
    index = 0
    current_hour = plot_dates[0].hour
    sun_indexes = []

    city_name = 'Stockholm'
    a = Astral()
    a.solar_depression = 'civil'
    city = a[city_name]

    sun = city.sun(plot_dates[0], local=True)

    graph_dates.append(plot_dates[0].strftime('%Y-%m-%d %H:%M:%S'))

    if (plot_dates[index].hour >= sun['sunrise'].hour and
            plot_dates[index].hour <= sun['sunset'].hour):
        sun_indexes.append(1)
    else:
        sun_indexes.append(0)

    for data in diff_array:
        if (plot_dates[index].hour > current_hour):
            graph_data.append(sum_value)
            sum_value = 0
            sum_value = sum_value + int(data)
            current_hour = current_hour + 1

            if (plot_dates[index].hour >= sun['sunrise'].hour and
                    plot_dates[index].hour <= sun['sunset'].hour):
                sun_indexes.append(1)
            else:
                sun_indexes.append(0)

            graph_dates.append(plot_dates[index].strftime('%Y-%m-%d %H:%M:%S'))
        elif (plot_dates[index].hour < current_hour):
            graph_data.append(sum_value)
            sum_value = 0
            sum_value = sum_value + int(data)
            current_hour = plot_dates[index].hour
            sun = city.sun(plot_dates[index], local=True)
            if (plot_dates[index].hour >= sun['sunrise'].hour and
                    plot_dates[index].hour <= sun['sunset'].hour):
                sun_indexes.append(1)
            else:
                sun_indexes.append(0)

            graph_dates.append(plot_dates[index].strftime('%Y-%m-%d %H:%M:%S'))
        else:
            sum_value = sum_value + int(data)

        index = index + 1

    graph_data.append(sum_value)

    return graph_dates, graph_data, sun_indexes
Ejemplo n.º 17
0
def get_sunrise_sunset():
    city = 'San Francisco'
    a = Astral()
    a.solar_depression = 'civil'
    city = a[city]
    sun = city.sun(date=datetime.now(), local=True)
    if now() >= sun['sunset']:
        sun = city.sun(date=datetime.now()+timedelta(days=1), local=True)
    return sun['sunrise'], sun['sunset']
Ejemplo n.º 18
0
def draw_astronomical(city_name, geo_data):
    datetime_day_start = datetime.datetime.now().replace(hour=0,
                                                         minute=0,
                                                         second=0,
                                                         microsecond=0)

    a = Astral()
    a.solar_depression = 'civil'

    city = Location()
    city.latitude = geo_data["latitude"]
    city.longitude = geo_data["longitude"]
    city.timezone = geo_data["timezone"]

    answer = ""
    moon_line = ""
    for time_interval in range(72):

        current_date = (datetime_day_start +
                        datetime.timedelta(hours=1 * time_interval)).replace(
                            tzinfo=pytz.timezone(geo_data["timezone"]))
        sun = city.sun(date=current_date, local=False)

        dawn = sun['dawn']  # .replace(tzinfo=None)
        dusk = sun['dusk']  # .replace(tzinfo=None)
        sunrise = sun['sunrise']  # .replace(tzinfo=None)
        sunset = sun['sunset']  # .replace(tzinfo=None)

        if current_date < dawn:
            char = " "
        elif current_date > dusk:
            char = " "
        elif dawn < current_date and current_date < sunrise:
            char = u"─"
        elif sunset < current_date and current_date < dusk:
            char = u"─"
        elif sunrise < current_date and current_date < sunset:
            char = u"━"

        answer += char

        # moon
        if time_interval % 3 == 0:
            moon_phase = city.moon_phase(
                date=datetime_day_start +
                datetime.timedelta(hours=time_interval))
            moon_phase_emoji = constants.MOON_PHASES[
                int(math.floor(moon_phase * 1.0 / 28.0 * 8 + 0.5)) %
                len(constants.MOON_PHASES)]
            if time_interval in [0, 24, 48, 69]:
                moon_line += moon_phase_emoji + " "
            else:
                moon_line += "   "

    answer = moon_line + "\n" + answer + "\n"
    answer += "\n"
    return answer
Ejemplo n.º 19
0
def sunrise_time():
	from astral import Astral

	astr_object = Astral()
	astr_object.solar_depression = "civil"
	try: return astr_object[CITY].sun(local=True)["sunrise"]
	except Exception as error:
		ErrorWriter.write_error(error)
		return None
Ejemplo n.º 20
0
def get_sun(date="today", depression="astronomical", cityname="Boston"):
    astral = Astral()
    astral.solar_depression = depression
    city = astral[cityname]
    calendar = parsedatetime.Calendar()
    dateinfo = calendar.parse(date)
    date_ts = time.mktime(dateinfo[0])
    date_dt = datetime.fromtimestamp(date_ts)
    return city.sun(date=date_dt, local=True)
Ejemplo n.º 21
0
def sunset():
    city_name = 'Minneapolis'
    a = Astral()
    a.solar_depression = 'civil'

    city = a[city_name]
    sun = city.sun(date=datetime.datetime.now(), local=True)

    return 'Sunset for {}: {}'.format(city_name, sun['sunset'])
Ejemplo n.º 22
0
def api_v1():
    astral = Astral()
    astral.solar_depression = "civil"
    astral.depression = 6.0

    city = astral["Toronto"]

    response = {
        "is_day": False,
        "is_night": False,
        "is_civil_twlight": False,
        "is_nautical_twlight": False,
        "is_astronomical_twilight": False,
        "is_blue_hour": False,
        "is_golden_hour": False,
        "solar_zenith_angle": city.solar_zenith(),
        "solar_elevation_angle": city.solar_elevation(),
        "solar_azimuth_angle": city.solar_azimuth(),
        "times_of_day": city.sun(),
    }

    current_datetime = datetime.datetime.now(city.tz)

    if city.sunrise() < current_datetime < city.sunset():
        response["is_day"] = True
    else:
        response["is_night"] = True

    if -6 <= city.solar_zenith() <= 0:
        response["is_civil_twlight"] = True
        response["is_day"] = False
        response["is_night"] = False
    elif -12 <= city.solar_zenith() <= -6:
        response["is_nautical_twlight"] = True
        response["is_day"] = False
        response["is_night"] = False
    elif -18 <= city.solar_zenith() <= -12:
        response["is_astronomical_twilight"] = True
        response["is_day"] = False
        response["is_night"] = False

    if -6 <= city.solar_zenith() <= -4:
        response["is_blue_hour"] = True
    elif -4 <= city.solar_zenith() <= 6:
        response["is_golden_hour"] = True

    if 0 <= city.moon_phase() < 7:
        response["moon_phase"] = "new-moon"
    elif 7 <= city.moon_phase() < 14:
        response["moon_phase"] = "first-quarter"
    elif 14 <= city.moon_phase() < 21:
        response["moon_phase"] = "full-moon"
    elif 21 <= city.moon_phase():
        response["moon_phase"] = "last-quarter"

    return jsonify(response)
Ejemplo n.º 23
0
def sun(request):
    """
    Return sunrise, sunset etc. times.
    """

    a = Astral()
    a.solar_depression = 'civil'
    l = Location()

    # l.name = 'Lapinlahden sairaala'
    # l.region = 'Helsinki'

    lat = request.GET.get('lat')
    lon = request.GET.get('lon')
    if lat is None or lon is None:
        l.latitude = 60.167761
        l.longitude = 24.9118141
        l.loc_source = 'default'
    else:
        l.latitude = float(lat)
        l.longitude = float(lon)
        l.loc_source = 'request'
    l.timezone = 'UTC'
    l.elevation = 0
    timeformat = request.GET.get('timeformat', 'epoch')
    date_str = request.GET.get('date')
    format_str = request.GET.get('format', 'json')
    date = datetime.datetime.now().date()
    if date_str is not None:
        date = parse(date_str).date()
        pass
    sundata = {
        'now': datetime.datetime.now(tz=pytz.UTC),  # .astimezone(pytz.UTC),
        'date': date.strftime('%Y-%m-%d'),
        'lat': l.latitude,
        'lon': l.longitude,
        'loc_source': l.loc_source,
    }

    try:
        sun = l.sun(date=date, local=False)
    except AstralError as e:
        return HttpResponse(json.dumps({'error': str(e)}),
                            content_type='application/json')
    for k in ['dawn', 'sunrise', 'noon', 'sunset', 'dusk']:
        sundata[k] = sun[k]
    if timeformat == 'iso':
        for k in sundata.keys():
            if isinstance(sundata[k], datetime.datetime):
                sundata[k] = sundata[k].isoformat()
    else:  # timeformat == 'epoch':
        for k in sundata.keys():
            if isinstance(sundata[k], datetime.datetime):
                sundata[k] = int(sundata[k].timestamp())
    res_str = json.dumps(sundata, indent=2)
    return HttpResponse(res_str, content_type='application/json')
Ejemplo n.º 24
0
def its_after_sunset(city_name):
    a = Astral()
    a.solar_depression = 'civil'
    city = a[city_name]
    sun = city.sun(date=date.today(), local=True)
    sunset_today = (sun['sunset']).replace(tzinfo=None)
    if sunset_today < datetime.today():
        return True
    else:
        return False
Ejemplo n.º 25
0
def SetSunTimes():
    cityName = "London"
    a = Astral()
    a.solar_depression = "civil"
    city = a[cityName]
    sun = city.sun(date=datetime.now(), local=True)
    variables.Set("dawn", str(sun['dawn'].strftime("%H:%M")))
    variables.Set("sunrise", str(sun['sunrise'].strftime("%H:%M")))
    variables.Set("sunset", str(sun['sunset'].strftime("%H:%M")))
    variables.Set("dusk", str(sun['dusk'].strftime("%H:%M")))
Ejemplo n.º 26
0
def get_sun():
    a = Astral()
    a.solar_depression = 'civil'
    city = a['Helsinki']
    sun = city.sun(date=datetime.now(), local=True)
    sunset = sun['dusk']
    sun = city.sun(date=datetime.now() + timedelta(days=1), local=True)
    sunrise = sun['dawn']

    return sunrise, sunset
Ejemplo n.º 27
0
def sun_api():
    data = {}
    city_name = 'Denver'
    a = Astral()
    a.solar_depression = 'civil'
    city = a[city_name]
    sun = city.sun(date=dt.datetime.today(), local=True)
    data = {k: sun[k].hour * 60 + sun[k].minute for k in sun}
    data['moon_phase'] = city.moon_phase()
    return data
Ejemplo n.º 28
0
def its_between_dawn_sunset(city_name):
    a = Astral()
    a.solar_depression = 'civil'
    city = a[city_name]
    sun = city.sun(date=date.today(), local=True)
    dawn_today = (sun['dawn']).replace(tzinfo=None)
    sunset_today = (sun['sunset']).replace(tzinfo=None)
    if (dawn_today < datetime.today()) and (sunset_today > datetime.today()):
        return True
    else:
        return False
def check_if_dark():
    from astral import Astral
    city_name = 'Kiev'
    a = Astral()
    a.solar_depression = 'civil'
    city = a[city_name]
    sun = city.sun(date=datetime.datetime.now(), local=True)
    T = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=2)))
    if (sun['sunrise'] < T < sun['sunset']):
        return False
    return True
Ejemplo n.º 30
0
def its_light_in(city_name):
    a = Astral()
    a.solar_depression = 'civil'
    city = a[city_name]
    sun = city.sun(date=date.today(), local=True)
    dawn_today = (sun['dawn']).replace(tzinfo=None)

    if dawn_today < datetime.today():
        return True
    else:
        return False
Ejemplo n.º 31
0
    def __init__(self):
        city_name = config.get('ASTRA_CITY')
        a = Astral()
        a.solar_depression = 'civil'

        self.__city = a[city_name]
        self.__today = None
        self.__sun = None
        self.__mode = None
        self.__timezone = pytz.timezone(self.__city.timezone)
        self.is_day()
Ejemplo n.º 32
0
 def auto(self,
          action: str = 'on',
          sun_state: str = 'sunset',
          offset: int = 0):
     a = Astral()
     a.solar_depression = 'civil'
     city = a[settings.LOCATION]
     sun = city.sun(date=datetime.now(), local=True)
     if datetime.now(sun[sun_state].tzinfo) >= sun[sun_state] + timedelta(
             seconds=offset):
         {'on': self.on, 'off': self.off}[action]()
Ejemplo n.º 33
0
def initAstral(self):
    a = Astral()
    a.solar_depression = 'civil'
    l = Location()
    l.name = 'Dolbeau-Mistassini'
    l.region = 'Canada'
    l.latitude = 48.9016
    l.longitude = -72.2156
    l.timezone = 'America/Montreal'
    l.elevation = 139
    self.location = l
Ejemplo n.º 34
0
def sunyears(start_year, end_year):
    city_name = 'London'
    a = Astral()
    a.solar_depression = 'civil'
    city = a[city_name]

    sun_times = {}

    print('Information for %s/%s\n' % (city_name, city.region))

    timezone = city.timezone
    print('Timezone: %s' % timezone)

    print(' Latitude: %.02f; Longitude: %.02f\n' %
          (city.latitude, city.longitude))

    delta = datetime.timedelta(days=1)

    for year in range(start_year, end_year + 1):
        # Loop through all days in year
        start_date = datetime.date(year, 1, 1)
        end_date = datetime.date(year, 12, 31)
        d = start_date
        while d <= end_date:

            sun = city.sun(d, local=True)
            # print('Dawn:    %s' % str(sun['dawn']))
            # print('Sunrise: %s' % str(sun['sunrise']))
            # print('Noon:    %s' % str(sun['noon']))
            # print('Sunset:  %s' % str(sun['sunset']))
            # print('Dusk:    %s' % str(sun['dusk']))
            # pprint(sun)

            sun_times[json_serial(d)] = sun
            # print(json.dumps(sun_times, default=json_serial,
            #      indent=4, sort_keys=True))

            d += delta

    # print(json.dumps(sun_times, default=json_serial))
    outfilename = "suntimes-{}-{}".format(start_year, end_year)
    outfilename = os.path.join("data", outfilename)
    mkdir("data")

    with open(outfilename + ".json", "w") as outfile:
        json.dump(sun_times,
                  outfile,
                  default=json_serial,
                  indent=4,
                  separators=(',', ': '),
                  sort_keys=True)

    with open(outfilename + ".min.json", "w") as outfile:
        json.dump(sun_times, outfile, default=json_serial)
Ejemplo n.º 35
0
def setup_location():
    global city

    city_name = 'Bucharest'
    a = Astral()
    a.solar_depression = 'civil'
    city = a[city_name]
    print('Solar data for %s/%s\n' % (city_name, city.region))

    timezone = city.timezone
    print('Timezone: %s' % timezone)
Ejemplo n.º 36
0
def SunUpDown(location):
    a = Astral()
    a.solar_depression = 'civil'
    timezone = location.timezone
    Now = strftime("%H:%M", localtime())
    dt = datetime.datetime.fromtimestamp(time.mktime(localtime()))
    tz = pytz.timezone("Europe/Berlin")
    dtn = tz.localize(dt)
    dtnT = dtn + datetime.timedelta(days=1)
    sun = location.sun(dtn, local=True)
    sunT = location.sun(dtnT, local=True)
    if (sun['sunrise'].hour < 10):
        Sunrise = '0' + str(sun['sunrise'].hour) + ':'
    else:
        Sunrise = str(sun['sunrise'].hour) + ':'
    if (sun['sunrise'].minute < 10):
        Sunrise = Sunrise + '0' + str(sun['sunrise'].minute)
    else:
        Sunrise = Sunrise + str(sun['sunrise'].minute)

    if (sunT['sunrise'].hour < 10):
        SunriseT = '0' + str(sunT['sunrise'].hour) + ':'
    else:
        SunriseT = str(sunT['sunrise'].hour) + ':'
    if (sunT['sunrise'].minute < 10):
        SunriseT = SunriseT + '0' + str(sunT['sunrise'].minute)
    else:
        SunriseT = SunriseT + str(sunT['sunrise'].minute)

    if (sun['sunset'].hour < 10):
        Sunset = '0' + str(sun['sunset'].hour) + ':'
    else:
        Sunset = str(sun['sunset'].hour) + ':'
    if (sun['sunset'].minute < 10):
        Sunset = Sunset + '0' + str(sun['sunset'].minute)
    else:
        Sunset = Sunset + str(sun['sunset'].minute)

    if (sunT['sunset'].hour < 10):
        SunsetT = '0' + str(sunT['sunset'].hour) + ':'
    else:
        SunsetT = str(sunT['sunset'].hour) + ':'
    if (sunT['sunset'].minute < 10):
        SunsetT = SunsetT + '0' + str(sunT['sunset'].minute)
    else:
        SunsetT = SunsetT + str(sunT['sunset'].minute)
    '''
    print sun['sunrise'], sun['sunset']
    print
    print sunT['sunrise'], sunT['sunset']
    print '-------------'
    '''
    return Sunrise, Sunset, SunriseT, SunsetT, sun['sunrise'], sun['sunset'], (
        (dtn > sun['sunrise']) and (dtn < sun['sunset']))
Ejemplo n.º 37
0
def test_Astral():
    location_name = 'Jubail'

    dd = Astral()
    dd.solar_depression = 'civil'

    location = dd[location_name]
    assert location.timezone == 'Asia/Riyadh'

    sun = location.sun()
    sunrise = location.sunrise(local=True)
    assert sunrise == sun['sunrise']
Ejemplo n.º 38
0
    def __init__(self, timeInterval, keepRunning):
        self.log = logging.getLogger('status_archiver')
        self.logfile = path +'status_' + datetime.datetime.now().strftime('%m-%d-%y') + '.log'
        city_name = 'San Francisco'
        a = Astral()
        a.solar_depression = 'astronomical'
        city = a[city_name]

        timezone = city.timezone
        sun = city.sun(date=datetime.date(2009, 4, 22), local=True)
        self.start = sun['dusk']
        self.stop = sun['dawn']
Ejemplo n.º 39
0
def main():
	a = Astral()
	a.solar_depression = 'civil'
	city = a['Birmingham']
	timezone = city.timezone
	sun = city.sun(date=datetime.date.today(), local=True)
	if is_light_outside(sun['dawn'], sun['dusk']):
		logger.info("Its light outside, switching off...")
		switch_off()
	else:
		logger.info("Its dark outside, switching on...")
		switch_on()
Ejemplo n.º 40
0
 def get_light_state(self):
     astral = Astral()
     astral.solar_depression = "civil"
     astral_city = astral["Perth"]
     now = datetime.datetime.now(pytz.timezone('Australia/Perth'))
     astral_city_sun = astral_city.sun(date=now, local=True)
     if (astral_city_sun['sunrise'] - datetime.timedelta(hours=1)) < now < astral_city_sun['sunset']:
         return "daylight"
     elif 1 <= now.hour <= 5:
         return "witching"
     else:
         return "evening"
Ejemplo n.º 41
0
def getSunTimes():
    city_name = TIMING_CITY
    a = Astral()
    a.solar_depression = 'civil'
    city = a[city_name]
    timezone = city.timezone
    sun = city.sun(date=datetime.datetime.now(), local=True)
    sunriseSeconds = ((sun['sunrise']).hour * 60 * 60) + (
        (sun['sunrise']).minute * 60)
    sunsetSeconds = ((sun['sunset']).hour * 60 * 60) + (
        (sun['sunset']).minute * 60)
    return sunriseSeconds, sunsetSeconds
Ejemplo n.º 42
0
def plot_nightshade(df, ax, **kwargs):
    a = Astral()
    a.solar_depression = 'civil'
    city = a['wellington']
    ymin, ymax = ax.get_ylim()
    
    for day in pd.date_range(df.index[0].date(), df.index[-1].date()):
        sun1 = city.sun(date=day - dt.timedelta(days=1))
        sun2 = city.sun(date=day, local=True)
        sunset = sun1['sunset'].replace(tzinfo=None)
        sunrise = sun2['sunrise'].replace(tzinfo=None)
        night = pd.DataFrame(index=[sunset, sunrise], 
		             data=dict(shade=[ymax, ymax]))
        night.shade.plot(kind='area', ax=ax, color='0.9', alpha=0.5, **kwargs)
Ejemplo n.º 43
0
def sunyears(start_year, end_year):
    city_name = 'London'
    a = Astral()
    a.solar_depression = 'civil'
    city = a[city_name]

    sun_times = {}

    print('Information for %s/%s\n' % (city_name, city.region))

    timezone = city.timezone
    print('Timezone: %s' % timezone)

    print(' Latitude: %.02f; Longitude: %.02f\n' %
          (city.latitude, city.longitude))

    delta = datetime.timedelta(days=1)

    for year in range(start_year, end_year+1):
        # Loop through all days in year
        start_date = datetime.date(year, 1, 1)
        end_date = datetime.date(year, 12, 31)
        d = start_date
        while d <= end_date:

            sun = city.sun(d, local=True)
            # print('Dawn:    %s' % str(sun['dawn']))
            # print('Sunrise: %s' % str(sun['sunrise']))
            # print('Noon:    %s' % str(sun['noon']))
            # print('Sunset:  %s' % str(sun['sunset']))
            # print('Dusk:    %s' % str(sun['dusk']))
            # pprint(sun)

            sun_times[json_serial(d)] = sun
            # print(json.dumps(sun_times, default=json_serial,
            #      indent=4, sort_keys=True))

            d += delta

    # print(json.dumps(sun_times, default=json_serial))
    outfilename = "suntimes-{}-{}".format(start_year, end_year)
    outfilename = os.path.join("data", outfilename)
    mkdir("data")

    with open(outfilename + ".json", "w") as outfile:
        json.dump(sun_times, outfile, default=json_serial,
                  indent=4, separators=(',', ': '), sort_keys=True)

    with open(outfilename + ".min.json", "w") as outfile:
        json.dump(sun_times, outfile, default=json_serial)
Ejemplo n.º 44
0
	def getRainLevel(self):
		if self.Weather == None:
			return "norain"
		
		city_name = 'London'
		a = Astral()
		a.solar_depression = 'civil'
		city = a[city_name]
		now = datetime.datetime.utcnow().replace(tzinfo=utc)
		sun = city.sun(date=datetime.datetime.now(), local=True)
		
		if now < sun['dawn']:
			#night
			weatherNum = self.Weather.getWeatherTypeNum(0, 1)
		elif now < sun['sunrise']:
			#sunrise
			weatherNum = self.Weather.getWeatherTypeNum()
		elif now < sun['sunset']:
			#day
			weatherNum = self.Weather.getWeatherTypeNum()
		elif now < sun['dusk']:
			#sunset
			weatherNum = self.Weather.getWeatherTypeNum(0, 1)
		else:
			#night
			weatherNum = self.Weather.getWeatherTypeNum(0, 1)
		
		if 0 <= int(weatherNum) <= 8:
			return "norain"
		elif 9 <= int(weatherNum) <= 10:
			return "lightrain"
		elif int(weatherNum) == 11:
			return "drizzel"
		elif int(weatherNum) == 12:
			return "lightrain"
		elif 13 <= int(weatherNum) <= 15:
			return "heavyrain"
		elif 16 <= int(weatherNum) <= 27:
			return "norain"
		elif 28 <= int(weatherNum) <= 29:
			return "heavyrain"
		else:
			return "norain"
Ejemplo n.º 45
0
    def func(self):
        """Display information about server or target"""
        account = self.account
        city_name = 'Phoenix' if not self.args else self.args
        a = Astral()
        a.solar_depression = 'civil'
        city = a[city_name]
        if not city:
            return
        timezone = city.timezone
        sun = city.sun(date=datetime.date.today(), local=True)

        account.msg('Information for %s/%s\n' % (city_name, city.region))
        account.msg('Timezone: %s' % timezone)
        account.msg('Latitude: %.02f; Longitude: %.02f' % (city.latitude, city.longitude))
        account.msg('Dawn:    %s' % str(sun['dawn']))
        account.msg('Sunrise: %s' % str(sun['sunrise']))
        account.msg('Noon:    %s' % str(sun['noon']))
        account.msg('Sunset:  %s' % str(sun['sunset']))
        account.msg('Dusk:    %s' % str(sun['dusk']))
Ejemplo n.º 46
0
def special_case(table,column,data,index,repeats):
	print 'special_case funk\n'
	"""This function treats the rain and sun categories different from the others, because
	they can have repeating zeros. The RAd_Flux can only have a certain number of zeores thought, 
	whereas the rain columns can have unlimited zeros.
	"""
	
	special_case = False
	if (column == 'RAIN_IN_TOTAL_Tot' and data[column][index] == 0) or (column == 'PRC_Tot' and data[column][index] <= .02):
		special_case = True
	
	if column == 'RAD_FLUX': 
		repeat_times = [pd.to_datetime(t) for t in  list(data['TmStamp'][index - (repeats - 1):index + 1])]
		city_name = 'Chicago'
		a = Astral()
		a.solar_depression = 'civil'
		city = a[city_name]
		sun = city.sun(date=repeat_times[-1], local=True)
		# get rid of timezone awareness to be able to compare the repeating 
			# datetimes which are timezone unaware by reinstantiating them as new datetime objects
		dawn = datetime(sun['dawn'].year,sun['dawn'].month,sun['dawn'].day ,sun['dawn'].hour,round_minutes(sun['dawn'].minute))
		dusk = sun['dusk'] - timedelta(days=1)
		dusk = datetime(dusk.year,dusk.month,dusk.day,dusk.hour,round_minutes(dusk.minute))
		night_overlap_allowance = 8 #allowed to be repeating 2 hrs before or after dawn/dusk
		# Check to see if all/majority of repeating times fall within the nighttime
			# If so, then the repeats are ignored
		if repeat_times[0] >= dusk and repeat_times[-1] <= dawn:
			special_case = True
		if repeat_times[0] < dusk and repeat_times[-1] > dusk and repeat_times[-1] <= dawn:
			len_prior_to_dusk = len(repeat_times[:repeat_times.index(dusk)])
			if len_prior_to_dusk < night_overlap_allowance:
				special_case = True
		if repeat_times[0] >= dusk and repeat_times[0] < dawn and repeat_times[-1] > dawn:
			len_prior_to_dawn = len(repeat_times[repeat_times.index(dawn) + 1:])
			if len_prior_to_dawn < night_overlap_allowance:
				special_case = True

	if special_case:
		return True
	else:
		return False
Ejemplo n.º 47
0
def UpdateFile(sfile,scity):
  import datetime
  from astral import Astral

  a = Astral()
  a.solar_depression = 'civil'
  city = a[scity]
  sun = city.sun(date=datetime.date.today(), local=True)

  ok=1
  try:
    datafile = open(sfile,'w')
  except:
    ok=0

  if ok == 1:
    datafile.write(strftime('%H%M%S',datetime.datetime.timetuple(sun['dawn']))+'\n')
    datafile.write(strftime('%H%M%S',datetime.datetime.timetuple(sun['sunrise']))+'\n')
    datafile.write(strftime('%H%M%S',datetime.datetime.timetuple(sun['noon']))+'\n')
    datafile.write(strftime('%H%M%S',datetime.datetime.timetuple(sun['sunset']))+'\n')
    datafile.write(strftime('%H%M%S',datetime.datetime.timetuple(sun['dusk']))+'\n')
    datafile.close()
Ejemplo n.º 48
0
def testAstral():
    city_name = "Jubail"

    dd = Astral()
    dd.solar_depression = "civil"

    city = dd[city_name]
    assert city.timezone == "Asia/Riyadh"

    print("Information for %s/%s\n" % (city_name, city.country))

    timezone = city.timezone
    print("Timezone: %s" % timezone)

    loc_tz = pytz.timezone(timezone)
    print("Latitude: %.02f; Longitude: %.02f\n" % (city.latitude, city.longitude))

    sun = city.sun()
    sunrise = city.sunrise(local=True)
    assert sunrise == sun["sunrise"]

    rahukaalam = city.rahukaalam()
Ejemplo n.º 49
0
SLEEP_WHEN_DARK = True
IMAGE_RESOLUTION = (1600, 1200)
#IMAGE_RESOLUTION = (800, 600)
MOTION_RESOLUTION = (800, 600)
SAVE_MOTION_IMAGES = True
CROP_IMAGES = True # Crop to lower half of the image


############################################################
# Setup

logging.basicConfig(level=getattr(logging, LOGLEVEL.upper()),
                    filename=os.path.join('images', 'log.txt'))

a = Astral()
a.solar_depression = 3
location = a['Berlin']

# Cologne:
location.latitude = 50.9534001
location.longitude = 6.9548886
location.elevation = 56


motion_mask = matplotlib.image.imread('motion_mask.png')[..., 0]

if CROP_IMAGES:
    motion_mask[:motion_mask.shape[0]//2][...] = 0


Ejemplo n.º 50
0
#!/usr/bin/python

# Schedule the door to close at the end of civil twilight, using the astral library. 


import os, sys
from astral import Astral

city_name = 'Seattle'

astral = Astral()
astral.solar_depression = 'civil'

city = astral[city_name]

sun = city.sun(local=True)

cmd = """echo '%s %s' | at %s""" % (sys.executable, 
                                    os.path.abspath(os.path.join(os.path.dirname(__file__), 'door/close.py')), 
                                    sun['dusk'].strftime("%H:%M"))
         
print cmd
os.system(cmd)
Ejemplo n.º 51
0
  sun = city.sun(date=t, local=True)

  if ((t>sun['sunrise']) & (t<sun['sunset'] + timedelta(minutes = 0))):
    return "day"
  else:
    return "night"

#========================================================================



city_name = 'Szombathely'

a = Astral(GoogleGeocoder)
a.solar_depression = 'civil'     # civil 6, nautical 12, astronomical 18
city = a[city_name]



os.system("ls " + path + "> list.txt") 
f = open('list.txt','r')
for line in f:
    line = line.rstrip('\n')
    if line[0]=="2":     
      if (night(line) == "night"):
        os.system("mv " + path + "/" + line + " " + path + "/night/" + line)
        print ("%s night %s:%s" %(line, line[8:10], line[10:12]))
      else:
        print ("%s day   %s:%s" %(line, line[8:10], line[10:12]))
Ejemplo n.º 52
0

print(
    "I apologize for my creators limited repository of available cities. He programmed with the WunderGround Api for many hours only to realize that one cant review the history of astronomy... sigh"
)
print("\n")

city_name = raw_input("Aaaaaaanyways what city would you like to search: ")


year = raw_input("Okay good! Now what year: ")
month = raw_input("Month: ")
day = raw_input("Day: ")

a = Astral()
a.solar_depression = "civil"
city = a[city_name]
sun = city.sun(date=datetime.date(int(year), int(month), int(day)), local=True)

t1 = str(sun["sunset"])
t1 = t1[11:19]

t2 = str(sun["sunrise"])
t2 = t2[11:19]
FMT = "%H:%M:%S"


start_dt = datetime.datetime.strptime(t2, "%H:%M:%S")
end_dt = datetime.datetime.strptime(t1, "%H:%M:%S")
diff = end_dt - start_dt
colon = str(diff).find(":")
def build_sun():
    a = Astral()
    a.solar_depression = "astronomical"
    city = a["Stockholm"]
    return city.sun(date=date.today(), local=True)
Ejemplo n.º 54
0
#!/usr/bin/env python
from __future__ import print_function
import time
from datetime import datetime
from heliotron import Bridge, presets
from astral import Astral

## Set up our timezone by feeding in the nearest major city, and then a
## more precise latitude/longitude (optional), to get the most accurate
## sunrise/sunset times as is possible
astral = Astral()
astral.solar_depression = 'civil'  # 6 degrees below horizon
city = astral.geocoder['Dallas']
city.latitude = 32.9614
city.longitude = -96.8259
sun = city.sun(date=datetime.now(), local=True)

print(city)
print('Dawn:    %s' % str(sun['dawn']))
print('Sunrise: %s' % str(sun['sunrise']))
print('Sunset:  %s' % str(sun['sunset']))
print('Dusk:    %s' % str(sun['dusk']))

bridge = Bridge(ip='10.0.0.42', app_name='testscript')
lights = bridge.get_lights()

## Set the lights to a jarring, eye-gouging 6500K (over 3 seconds)
print('Blinding you...')
for light in lights:
    print('- from %s' % light.name)
    light.set_kelvin(6500, secs=3)
Ejemplo n.º 55
0
def main():

	syslog.openlog(sys.argv[0])
	
	# Change location to nearest city.
	location = 'San Diego'  
	
	# Get the local sunset/sunrise times
	a = Astral()
	a.solar_depression = 'civil'
	city = a[location]
	timezone = city.timezone
	sun = city.sun(date=datetime.datetime.now(), local=True)

	if debug:
		print 'Information for {}/{}\n'.format(location, city.region)
		print 'Timezone: {}'.format(timezone)
		
		print 'Latitude: {:.02f}; Longitude: {:.02f}\n'.format(city.latitude, city.longitude)
		   
		print('Dawn:    {}'.format(sun['dawn']))
		print('Sunrise: {}'.format(sun['sunrise']))
		print('Noon:    {}'.format(sun['noon']))
		print('Sunset:  {}'.format(sun['sunset']))
		print('Dusk:    {}'.format(sun['dusk']))
		
	# Find the bulbs on the LAN
	scanner = BulbScanner()
	scanner.scan(timeout=4)

	# Specific ID/MAC of the bulbs to set 
	porch_info = scanner.getBulbInfoByID('ACCF235FFFEE')
	livingroom_info = scanner.getBulbInfoByID('ACCF235FFFAA')
	
	if porch_info:
		bulb = WifiLedBulb(porch_info['ipaddr'])
		bulb.refreshState()
		
		timers = bulb.getTimers()

		# Set the porch bulb to turn on at dusk using timer idx 0
		syslog.syslog(syslog.LOG_ALERT, 
			"Setting porch light to turn on at {}:{:02d}".format(sun['dusk'].hour, sun['dusk'].minute))
		dusk_timer = LedTimer()
		dusk_timer.setActive(True)
		dusk_timer.setRepeatMask(LedTimer.Everyday)
		dusk_timer.setModeWarmWhite(35)
		dusk_timer.setTime(sun['dusk'].hour, sun['dusk'].minute)
		timers[0] = dusk_timer
		
		# Set the porch bulb to turn off at dawn using timer idx 1
		syslog.syslog(syslog.LOG_ALERT, 
			"Setting porch light to turn off at {}:{:02d}".format(sun['dawn'].hour, sun['dawn'].minute))
		dawn_timer = LedTimer()
		dawn_timer.setActive(True)
		dawn_timer.setRepeatMask(LedTimer.Everyday)
		dawn_timer.setModeTurnOff()
		dawn_timer.setTime(sun['dawn'].hour, sun['dawn'].minute)
		timers[1] = dawn_timer
		
		bulb.sendTimers(timers)

	else:
		print "Can't find porch bulb"
			
	if livingroom_info:
		bulb = WifiLedBulb(livingroom_info['ipaddr'])
		bulb.refreshState()
		
		timers = bulb.getTimers()

		# Set the living room bulb to turn on at sunset using timer idx 0
		syslog.syslog(syslog.LOG_ALERT, 
			"Setting LR light to turn on at {}:{:02d}".format(sun['sunset'].hour, sun['sunset'].minute))
		sunset_timer = LedTimer()
		sunset_timer.setActive(True)
		sunset_timer.setRepeatMask(LedTimer.Everyday)
		sunset_timer.setModeWarmWhite(50)
		sunset_timer.setTime(sun['sunset'].hour, sun['sunset'].minute)
		timers[0] = sunset_timer

		# Set the living room bulb to turn off at a fixed time
		off_timer = LedTimer()
		off_timer.setActive(True)
		off_timer.setRepeatMask(LedTimer.Everyday)
		off_timer.setModeTurnOff()
		off_timer.setTime(23,30)
		timers[1] = off_timer
		
		bulb.sendTimers(timers)
	else:
		print "Can't find living room bulb"                   
Ejemplo n.º 56
0
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 = 365			# number of days
startDay = 0			# Initial day


#Select the geographic location. Refer to the Astral plugin to see available locations (or give a lon+lat)
city_name = 'Amsterdam' 
a = Astral()
a.solar_depression = 'civil'
city = a[city_name]



#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
penetrationEV 				= 10 
penetrationPHEV 			= 15 
penetrationPV				= 100
Ejemplo n.º 57
0
import datetime
from astral import Astral

if __name__ == '__main__':
    astral = Astral()
    city_name = "New York"
    astral.solar_depression = "civil"
    city = astral[city_name]
    sun_data = city.sun(date=datetime.date.today(), local=True)
    print('Sunset:  %s' % str(sun_data['sunset']))
    print('Dusk:    %s' % str(sun_data['dusk']))
Ejemplo n.º 58
-2
def brightness(city, at=None) -> str:
    """

    :param city: str e.g. "Amsterdam"
    :param at: datetime
    :return: str one of the values "night, dawn, day, dusk" depending on the time
    """

    if at is None:
        at = datetime.datetime.now()

    astral = Astral()
    astral.solar_depression = 'nautical'
    location = astral[city]
    sun = location.sun(date=at)
    at = pytz.timezone(location.timezone).localize(at)

    dawn = sun['dawn']
    sunrise = sun['sunrise']
    sunset = sun['sunset']
    dusk = sun['dusk']

    if at >= dawn and at < sunrise:
        return DAWN
    if at >= sunrise and at < sunset:
        return DAY
    if at >= sunset and at < dusk:
        return DUSK

    return NIGHT