Esempio n. 1
0
def initPixels():
    global initialized
    if initialized:
        return
    # initialize pixels and set location info
    global neocalThread
    global pixels
    global location
    for n in reversed(range(neopixel_length)):
        pixels[n] = white
        sleep(timeout)
    sleep(1.5)
    for n in range(neopixel_length):
        pixels[n] = black
        sleep(timeout)

    location = LocationInfo(city, region, latitude, longitude)

    # Create neocal thread, start immediately
    neocalThread = threading.Timer(0, run, ())
    neocalThread.start()
    if FILEMODE:
        hueGPIOThread = threading.Timer(0, loadHueColor, ())
        hueGPIOThread.start()
    initialized = True
Esempio n. 2
0
 def calc_astral_day_time2(date: datetime.datetime, time, latitude, longitude):
     """
     Compute sun position for given coordinates and time.
     :param date: UTC date
     :param time: UTC time
     :param latitude: latitude
     :param longitude: longitude
     :return: D for Day, U for Dusk, N for Night, A pour Dawn (Aube in French)
     """
     loc = LocationInfo()
     loc.latitude = latitude
     loc.longitude = longitude
     sun_phases = sun(observer=loc.observer, date=date, dawn_dusk_depression=Depression.NAUTICAL)
     observation_time = datetime.datetime.combine(date, time, tzinfo=utc)
     if observation_time < sun_phases['dawn']:
         sun_phases = sun(observer=loc.observer, date=date - ONE_DAY, dawn_dusk_depression=Depression.NAUTICAL)
     elif observation_time > sun_phases['dusk']:
         sun_phases = sun(observer=loc.observer, date=date + ONE_DAY, dawn_dusk_depression=Depression.NAUTICAL)
     # The intervals and their interpretation
     interp = [
         {'from:': sun_phases['dawn'], 'to:': sun_phases['sunrise'], '=>': 'A'},
         {'from:': sun_phases['sunrise'], 'to:': sun_phases['sunset'], '=>': 'D'},
         {'from:': sun_phases['sunset'], 'to:': sun_phases['dusk'], '=>': 'U'},
     ]
     for intrv in interp:
         if intrv['from:'] <= observation_time <= intrv['to:']:
             return intrv['=>']
     return '?'
def suntimes(location,latitude,longitude):
   cachename = addonId + ".timezone"
   cachedata = cache.get(cachename)
   #cachedata = False
   if cachedata:
      zonecache = True
      local_timezone = cachedata
   else:
      zonecache = False
      local_timezone = datetime.datetime.now(datetime.timezone.utc).astimezone().tzinfo
      cache.set(cachename, local_timezone, expiration=datetime.timedelta(hours=12))

   cachename = addonId + "." + location
   cachedata = cache.get(cachename)
   #cachedata = False
   if cachedata:
      start = cachedata["start"]
      end = cachedata["end"]
      times = {"start": start, "end": end, "local_timezone": local_timezone, "zonecache": zonecache, "timecache": True}
   else:
      city = LocationInfo(latitude=latitude, longitude=longitude)
      sundata = sun(city.observer, tzinfo=local_timezone)
      start = sundata["sunrise"].strftime("%H:%M:%S")
      end = sundata["sunset"].strftime("%H:%M:%S")
      times = {"start": start, "end": end, "local_timezone": local_timezone, "zonecache": zonecache, "timecache": False}
      cache.set(cachename, times, expiration=datetime.timedelta(hours=12))
   return times
Esempio n. 4
0
def _get_sun_information(day):
    lakewood = LocationInfo(name="Lakewood",
                            region="United States",
                            timezone="America/New_York",
                            latitude=41.4724629,
                            longitude=-81.802996)
    return sun(lakewood.observer, date=day, tzinfo=lakewood.timezone)
Esempio n. 5
0
def preprocess_gedi_gdf(path):
    """
    Takes a pathlib Path to a subsetted GEDI file that was processed by 
    gedi_to_vector into shapefile format. Returns a geodataframe that has been 
    quality filtered and with quality flags for sundown, beam type, and any other 
    variables that were used with gedi_to_vector.py
    """
    gdf = gpd.read_file(path)
    gdf['name'] = path.name
    power_test = lambda x: x in [
        "BEAM0101", "BEAM0110", "BEAM1000", "BEAM1011"
    ]
    gdf["is_power_beam"] = gdf['BEAM'].apply(power_test)
    gdf['delta_time'] = gdf['delta_time'].apply(
        convert_float_to_datetime)  # UTC is 7 hours ahead of Arizona
    gdf = gdf.set_index("delta_time")
    gdf = gdf.rename({
        "longitude_": "longitude",
        "latitude_b": "latitude"
    },
                     axis=1)
    gdf = gdf[(gdf["l2a_qualit"] == 1) & (gdf["l2b_qualit"] == 1)]
    # it's suggested in the GEDI L2B product doc to use nightime samples to reduce solar illumination bias. We add a flag here based
    # on local sunrise and sunset for the first sample in each track (the study area is small enough for this)
    city = LocationInfo("Phoenix",
                        "Arizona",
                        timezone=pytz.timezone("America/Phoenix"),
                        latitude=gdf.latitude[0],
                        longitude=gdf.longitude[0])
    s = sun(city.observer,
            date=datetime(gdf.index[0].year, gdf.index[0].month,
                          gdf.index[0].day),
            tzinfo=pytz.timezone("America/Phoenix"))
    gdf["is_sundown"] = (gdf.index < s['sunrise']) & (gdf.index > s['sunset'])
    return gdf
Esempio n. 6
0
 def test_Default(self):
     loc = LocationInfo()
     assert loc.name == "Greenwich"
     assert loc.region == "England"
     assert loc.timezone == "Europe/London"
     assert loc.latitude == pytest.approx(51.4733, abs=0.001)
     assert loc.longitude == pytest.approx(-0.0008333, abs=0.000001)
Esempio n. 7
0
def show_time(args):
    """
    Output fime for selected event.
    """
    init()
    from settings import LATITUDE, LONGITUDE
    s = Suncalc(LATITUDE, LONGITUDE, args.event)

    city = LocationInfo("Hamburg", "Germany", "Europe/Berlin", LATITUDE,
                        LONGITUDE)
    print((f"Information for {city.name}/{city.region}\n"
           f"Timezone: {city.timezone}\n"
           f"Latitude: {city.latitude}; Longitude: {city.longitude}\n"))

    local_dt = datetime.now(tz=city.tzinfo)
    thesun = sun(city.observer, date=local_dt, tzinfo=city.tzinfo)

    print((f'Dawn:    {thesun["dawn"]}\n'
           f'Sunrise: {thesun["sunrise"]}\n'
           f'Noon:    {thesun["noon"]}\n'
           f'Sunset:  {thesun["sunset"]}\n'
           f'Dusk:    {thesun["dusk"]}\n'))

    value = s.local_value(local_dt)

    print("Local {} is at {}".format(args.event, value))
Esempio n. 8
0
def test_date_events(opp):
    """Test retrieving next sun events."""
    utc_now = datetime(2016, 11, 1, 8, 0, 0, tzinfo=dt_util.UTC)
    from astral import LocationInfo
    import astral.sun

    utc_today = utc_now.date()

    location = LocationInfo(latitude=opp.config.latitude,
                            longitude=opp.config.longitude)

    dawn = astral.sun.dawn(location.observer, utc_today)
    dusk = astral.sun.dusk(location.observer, utc_today)
    midnight = astral.sun.midnight(location.observer, utc_today)
    noon = astral.sun.noon(location.observer, utc_today)
    sunrise = astral.sun.sunrise(location.observer, utc_today)
    sunset = astral.sun.sunset(location.observer, utc_today)

    assert dawn == sun.get_astral_event_date(opp, "dawn", utc_today)
    assert dusk == sun.get_astral_event_date(opp, "dusk", utc_today)
    assert midnight == sun.get_astral_event_date(opp, "midnight", utc_today)
    assert noon == sun.get_astral_event_date(opp, "noon", utc_today)
    assert sunrise == sun.get_astral_event_date(opp, SUN_EVENT_SUNRISE,
                                                utc_today)
    assert sunset == sun.get_astral_event_date(opp, SUN_EVENT_SUNSET,
                                               utc_today)
Esempio n. 9
0
    def __init__(self, connection: knxdclient.KNXDConnection,
                 loop: asyncio.AbstractEventLoop, scheduler: AsyncIOScheduler,
                 device_config: dict, core_config: dict, name: str):
        super().__init__(connection, loop, scheduler, device_config,
                         core_config, name)
        # sun configuration
        self.location_info = LocationInfo(
            self.core_config["location"]["name"],
            self.core_config["location"]["region"],
            self.core_config["location"]["timezone"],
            self.core_config["location"]["latitude"],
            self.core_config["location"]["longitude"])

        # automatic shading configuration
        self.automatic_shading_state = AutomaticShadingState.IDLE
        self.automatic_shading_sun_on = util.SwitchOnOffDelay(
            timedelta(minutes=5))
        self.automatic_shading_sun_off = util.SwitchOnOffDelay(
            timedelta(minutes=20))
        self.automatic_shading_sun_active = False
        self.automatic_shading_range = AutomaticShadingRange(
            self.device_config, self.location_info)

        # current position of the shade
        self.current_position_height = 0
        self.current_position_slat = 0
        self.current_day_night = DayNight.DAY

        # jobs
        self.scheduler_jobs = []

        # sensors
        self.enabled = False
        self.outdoor_brightness = 0.0
        self.setpoint_brightness = 20000.0
Esempio n. 10
0
def homepage():
    orgdate = '2018-03-04'
    cityinfo = "Dallas"
    options = 'Aberdeen, Abu Dhabi, Abu Dhabi, Abuja, Accra, Addis Ababa, Adelaide, Al Jubail, Albany, Albuquerque, Algiers, Amman, Amsterdam, Anchorage, Andorra la Vella, Ankara, Annapolis, Antananarivo, Apia, Ashgabat, Asmara, Astana, Asuncion, Athens, Atlanta, Augusta, Austin, Avarua, Baghdad, Baku, Baltimore, Bamako, Bandar Seri Begawan, Bangkok, Bangui, Banjul, Barrow-In-Furness, Basse-Terre, Basseterre, Baton Rouge, Beijing, Beirut, Belfast, Belgrade, Belmopan, Berlin, Bern, Billings, Birmingham, Birmingham, Bishkek, Bismarck, Bissau, Bloemfontein, Bogota, Boise, Bolton, Boston, Bradford, Brasilia, Bratislava, Brazzaville, Bridgeport, Bridgetown, Brisbane, Bristol, Brussels, Bucharest, Bucuresti, Budapest, Buenos Aires, Buffalo, Bujumbura, Burlington, Cairo, Canberra, Cape Town, Caracas, Cardiff, Carson City, Castries, Cayenne, Charleston, Charlotte, Charlotte Amalie, Cheyenne, Chicago, Chisinau, Cleveland, Columbia, Columbus, Conakry, Concord, Copenhagen, Cotonou, Crawley, Dakar, Dallas, Damascus, Dammam, Denver, Des Moines, Detroit, Dhaka, Dili, Djibouti, Dodoma, Doha, Douglas, Dover, Dublin, Dushanbe, Edinburgh, El Aaiun, Fargo, Fort-de-France, Frankfort, Freetown, Funafuti, Gaborone, George Town, Georgetown, Gibraltar, Glasgow, Greenwich, Guatemala, Hanoi, Harare, Harrisburg, Hartford, Havana, Helena, Helsinki, Hobart, Hong Kong, Honiara, Honolulu, Houston, Indianapolis, Islamabad, Jackson, Jacksonville, Jakarta, Jefferson City, Jerusalem, Juba, Jubail, Juneau, Kabul, Kampala, Kansas City, Kathmandu, Khartoum, Kiev, Kigali, Kingston, Kingston, Kingstown, Kinshasa, Koror, Kuala Lumpur, Kuwait, La Paz, Lansing, Las Vegas, Leeds, Leicester, Libreville, Lilongwe, Lima, Lincoln, Lisbon, Little Rock, Liverpool, Ljubljana, Lome, London, Los Angeles, Louisville, Luanda, Lusaka, Luxembourg, Macau, Madinah, Madison, Madrid, Majuro, Makkah, Malabo, Male, Mamoudzou, Managua, Manama, Manchester, Manchester, Manila, Maputo, Maseru, Masqat, Mbabane, Mecca, Medina, Melbourne, Memphis, Mexico, Miami, Milwaukee, Minneapolis, Minsk, Mogadishu, Monaco, Monrovia, Montevideo, Montgomery, Montpelier, Moroni, Moscow, Moskva, Mumbai, Muscat, N’Djamena, Nairobi, Nashville, Nassau, Naypyidaw, New Delhi, New Orleans, New York, Newark, Newcastle, Newcastle Upon Tyne, Ngerulmud, Niamey, Nicosia, Norwich, Nouakchott, Noumea, Nuku’alofa, Nuuk, Oklahoma City, Olympia, Omaha, Oranjestad, Orlando, Oslo, Ottawa, Ouagadougou, Oxford, P’yongyang, Pago Pago, Palikir, Panama, Papeete, Paramaribo, Paris, Perth, Philadelphia, Phnom Penh, Phoenix, Pierre, Plymouth, Podgorica, Port Louis, Port Moresby, Port of Spain, Port-Vila, Port-au-Prince, Portland, Portland, Porto-Novo, Portsmouth, Prague, Praia, Pretoria, Pristina, Providence, Quito, Rabat, Raleigh, Reading, Reykjavik, Richmond, Riga, Riyadh, Road Town, Rome, Roseau, Sacramento, Saint Helier, Saint Paul, Saint Pierre, Saipan, Salem, Salt Lake City, San Diego, San Francisco, San Jose, San Juan, San Marino, San Salvador, Sana, Sana’a, Santa Fe, Santiago, Santo Domingo, Sao Tome, Sarajevo, Seattle, Seoul, Sheffield, Singapore, Sioux Falls, Skopje, Sofia, Southampton, Springfield, Sri Jayawardenapura Kotte, St. George’s, St. John’s, St. Peter Port, Stanley, Stockholm, Sucre, Suva, Swansea, Swindon, Sydney, T’bilisi, Taipei, Tallahassee, Tallinn, Tarawa, Tashkent, Tbilisi, Tegucigalpa, Tehran, Thimphu, Tirana, Tirane, Tokyo, Toledo, Topeka, Torshavn, Trenton, Tripoli, Tunis, Ulaanbaatar, Ulan Bator, Vaduz, Valletta, Vienna, Vientiane, Vilnius, Virginia Beach, W. Indies, Warsaw, Washington DC, Wellington, Wichita, Willemstad, Wilmington, Windhoek, Wolverhampton, Yamoussoukro, Yangon, Yaounde, Yaren, Yerevan, Zagreb'
    cities = options.split(",")
    city = LocationInfo(cityinfo)
    timezone = city.timezone
    long = city.longitude
    lat = city.latitude
    date = datetime.strptime(orgdate, "%Y-%m-%d")
    suns = sun(city.observer, date=date)
    dawn = suns['dawn'].strftime("%H:%M:%S")
    sunrise = suns['sunrise'].strftime("%H:%M:%S")
    sunset = suns['sunset'].strftime("%H:%M:%S")
    dusk = suns['dusk'].strftime("%H:%M:%S")
    noon = suns['noon'].strftime("%H:%M:%S")
    table1 = {
        'city': city.name,
        'region': city.region,
        'timezone': timezone,
        'long': long,
        'lat': lat
    }
    table2 = {
        'date': orgdate,
        'dawn': dawn,
        'sunrise': sunrise,
        'sunset': sunset,
        'dusk': dusk,
        'noon': noon
    }
    return render_template('home.html',
                           cities=cities,
                           table1=table1,
                           table2=table2)
Esempio n. 11
0
    async def start(self) -> bool:
        """Initialize the PVSite object."""
        config = self._config

        site = config.site
        self._siteinfo = LocationInfo(site.name, site.region, site.tz,
                                      site.latitude, site.longitude)
        self._tzinfo = tz.gettz(config.site.tz)

        for inverter in config.inverters:
            try:
                i = inverter.get('inverter')
                invObject = Inverter(i.get('name'), i.get('url'),
                                     i.get('username'), i.get('password'),
                                     self._session)
                self._inverters.append(invObject)
            except Exception as e:
                _LOGGER.error(
                    f"An error occurred while setting up the inverters: {e}")
                return False

        if 'influxdb2' in config.keys():
            try:
                result = self._influxdb_client.start()
                if result is False:
                    return False
            except FailedInitialization:
                return False
        else:
            _LOGGER.warning("No support for InfluxDB included in YAML file")

        if 'mqtt' in config.keys():
            if not mqtt.start(config=config.mqtt):
                return False
        else:
            _LOGGER.warning("No support for MQTT included in YAML file")

        if 'settings' in config.keys() and 'sampling' in config.settings.keys(
        ):
            self._sampling_fast = config.settings.sampling.get(
                'fast', _DEFAULT_FAST)
            self._sampling_medium = config.settings.sampling.get(
                'medium', _DEFAULT_MEDIUM)
            self._sampling_slow = config.settings.sampling.get(
                'slow', _DEFAULT_SLOW)

        inverters = await asyncio.gather(*(inverter.start()
                                           for inverter in self._inverters))
        success = True
        for inverter in inverters:
            if inverter.get('keys', None) is None:
                _LOGGER.error(
                    f"Connection to inverter '{inverter.get('name')}' failed: {inverter.get('error', 'None')}"
                )
                success = False
        if not success:
            return False

        self._cached_keys = inverters[0].get('keys')
        return True
Esempio n. 12
0
def get_times():
    """Get sunrise/sunset times for default values in app"""
    try:
        mylocation = geocoder.ip('me')
        mylatlng = mylocation.latlng
        mytimezone = mylocation.json['raw']['timezone']
        loc = LocationInfo(latitude=mylatlng[0], longitude=mylatlng[1])
        s = sun.sun(loc.observer, datetime.datetime.now(), tzinfo=mytimezone)

        # adjustment to widen dawn/dusk window (quite short by default)
        adjustment = datetime.timedelta(minutes=20)
        times = {
            'dawn': (s['dawn'] - adjustment).time(),
            'sunrise': (s['sunrise'] + adjustment).time(),
            'sunset': (s['sunset'] - adjustment).time(),
            'dusk': (s['dusk'] + adjustment).time()
        }

    except:
        """For when no connection"""
        times = {
            'dawn': datetime.time(hour=5),
            'sunrise': datetime.time(hour=7),
            'sunset': datetime.time(hour=17),
            'dusk': datetime.time(hour=19)
        }

    return times
Esempio n. 13
0
def calc_astral_day_time(date: datetime.date, time, latitude, longitude):
    """
    Compute sun position for given coordinates and time.
    :param date: UTC date
    :param time: UTC time
    :param latitude: latitude
    :param longitude: longitude
    :return: D for Day, U for Dusk, N for Night, A for Dawn (Aube in French)
    """
    loc = LocationInfo()
    loc.latitude = latitude
    loc.longitude = longitude
    s = sun(loc.observer, date=date, dawn_dusk_depression=Depression.NAUTICAL)
    ret = '?'
    # The intervals and their interpretation
    interp = ({'from:': s['dusk'].time(), 'to:': s['dawn'].time(), '=>': 'N'},
              {'from:': s['dawn'].time(), 'to:': s['sunrise'].time(), '=>': 'A'},
              {'from:': s['sunrise'].time(), 'to:': s['sunset'].time(), '=>': 'D'},
              {'from:': s['sunset'].time(), 'to:': s['dusk'].time(), '=>': 'U'},
              )
    for intrv in interp:
        if (intrv['from:'] < intrv['to:']
                and intrv['from:'] <= time <= intrv['to:']):
            # Normal interval
            ret = intrv['=>']
        elif intrv['from:'] > intrv['to:'] \
                and (time >= intrv['from:'] or time <= intrv['to:']):
            # Change of day b/w the 2 parts of the interval
            ret = intrv['=>']

    return ret
Esempio n. 14
0
def test_date_events_default_date(hass):
    """Test retrieving next sun events."""
    utc_now = datetime(2016, 11, 1, 8, 0, 0, tzinfo=dt_util.UTC)
    from astral import LocationInfo
    import astral.sun

    utc_today = utc_now.date()

    location = LocationInfo(
        latitude=hass.config.latitude, longitude=hass.config.longitude
    )

    dawn = astral.sun.dawn(location.observer, date=utc_today)
    dusk = astral.sun.dusk(location.observer, date=utc_today)
    midnight = astral.sun.midnight(location.observer, date=utc_today)
    noon = astral.sun.noon(location.observer, date=utc_today)
    sunrise = astral.sun.sunrise(location.observer, date=utc_today)
    sunset = astral.sun.sunset(location.observer, date=utc_today)

    with patch("homeassistant.util.dt.now", return_value=utc_now):
        assert dawn == sun.get_astral_event_date(hass, "dawn", utc_today)
        assert dusk == sun.get_astral_event_date(hass, "dusk", utc_today)
        assert midnight == sun.get_astral_event_date(hass, "midnight", utc_today)
        assert noon == sun.get_astral_event_date(hass, "noon", utc_today)
        assert sunrise == sun.get_astral_event_date(hass, SUN_EVENT_SUNRISE, utc_today)
        assert sunset == sun.get_astral_event_date(hass, SUN_EVENT_SUNSET, utc_today)
Esempio n. 15
0
def zon(opofonder):
    city = LocationInfo()
    city.region = "Netherlands"

    ###voor nijverdal
    city.name = "Nijverdal"
    city.latitude = 52.366146
    city.longitude = 6.443098

    ###Voor Meppel
    if test():
        city.name = "Meppel"
        city.latitude = 52.701499
        city.longitude = 6.232482

    tijdzoneAmsterdam = timezone("Europe/Amsterdam")
    nu = datetime.datetime.now()
    if test():
        print(nu)
    city.timezone = tijdzoneAmsterdam

    s = sun(city.observer, date=nu, tzinfo=tijdzoneAmsterdam)
    if test():
        for k in ["dawn", "sunrise", "noon", "sunset", "dusk"]:
            print("%7s %s" % (k, s[k]))

    if opofonder == "onder":
        return (s["sunset"])
    if opofonder == "op":
        return (s["sunrise"])
Esempio n. 16
0
    def __init__(self, info: Optional[LocationInfo] = None):
        """Initializes the Location with a LocationInfo object.

            The tuple should contain items in the following order

            ================ =============
            Field            Default
            ================ =============
            name             Greenwich
            region           England
            time zone name   Europe/London
            latitude         51.4733
            longitude        -0.0008333
            ================ =============

            See the :attr:`timezone` property for a method of obtaining time zone
            names
        """

        self._location_info: LocationInfo
        self._solar_depression: float = Depression.CIVIL.value

        if not info:
            self._location_info = LocationInfo("Greenwich", "England",
                                               "Europe/London", 51.4733,
                                               -0.0008333)
        else:
            self._location_info = info
Esempio n. 17
0
    def index(self, latitude=None, longitude=None):
        if latitude:
            try:
                latitude = float(latitude)
            except ValueError:
                return 'latitude must be a floating point number'

        if longitude:
            try:
                longitude = float(longitude)
            except ValueError:
                return 'longitude must be a floating point number'

        # Default to Dublin, Ireland
        city = LocationInfo(latitude=(latitude or 53.427),
                            longitude=(longitude or -6.25))
        s = sun(city.observer, datetime.date.today())

        ret = 'Sunrise: %s<br/>\n' % (s['sunrise'].strftime('%H:%M'))
        ret += 'Sunset: %s<br/>\n' % (s['sunset'].strftime('%H:%M'))

        phasenum = moon.phase(datetime.date.today())

        if 14 < phasenum < 15:
            ret += 'Full moon'

        return ret
Esempio n. 18
0
 def __init__(self):
     self.time = None
     self.active = False
     self.period_on = None
     self.period_off = None
     self.location = LocationInfo('wyry', 'slaskie', 'Europe/Warsaw', 50.135250, 18.894160)
     self.sun_info = sun(self.location.observer, date=datetime.today())
Esempio n. 19
0
    def __init__(self, settings: Dict[str, Any]):
        self.log = logging.getLogger()
        signal.signal(signal.SIGINT, self.signal_handler)

        self.configure_logging(settings["log"])

        self.settings = settings
        if 'mqtt' in self.settings:
            self.mqtt_client = mqtt.Client(self.settings["mqtt"]["client_name"])
            self.mqtt_client.on_connect = self.on_connect
            self.mqtt_client.on_message = self.on_message
            self.mqtt_client.connect(self.settings["mqtt"]["server"])
            self.mqtt_client.loop_start()
        else:
            self.mqtt_client = None

        self.location = LocationInfo(**self.settings["location"])
        if 'watchdog' in self.settings:
            self.watchdog = SkyPiWatchdog(**self.settings["watchdog"])
            self.watchdog.start()
        else:
            self.watchdog = None

        self.file_managers: Dict[str, SkyPiFileManager] = {
            name: SkyPiFileManager(name=name, **kwargs)
            for (name, kwargs) in self.settings["files"].items()
        }
Esempio n. 20
0
def schedule_cron_jobs(lat, lon, config_path, channel, channel_config):
    path_to_source = os.path.dirname(
        os.path.dirname(os.path.realpath(__file__)))
    cron = CronTab(user=True)

    city = LocationInfo(name='',
                        region='',
                        timezone='',
                        latitude=lat,
                        longitude=lon)
    for i in range(1, 8):
        date = datetime.datetime.now() + datetime.timedelta(days=i)
        s = sun(city.observer, date=date)

        # s['sunrise']
        j = cron.new('python3 {} -c {} -ch {} -m open'.format(
            os.path.join(path_to_source, 'servo', 'move.py'), config_path,
            channel))
        j.setall(s['sunrise'] +
                 datetime.timedelta(minutes=channel_config['SUNRISE_BUFFER']))

        # s['sunset']
        j = cron.new('python3 {} -c {} -ch {} -m close'.format(
            os.path.join(path_to_source, 'servo', 'move.py'), config_path,
            channel))
        j.setall(s['sunset'] +
                 datetime.timedelta(minutes=channel_config['SUNSET_BUFFER']))

    cron.write(user=True)
Esempio n. 21
0
    def _setup(self):
        # Data Directory
        self._data_dir = initDataDir(self._thread.name)

        # Region
        region = getEnvVar(EnvVarName.REGION)
        if isEmpty(region):
            raise RuntimeError("Missing required environment variable: " + EnvVarName.REGION.name)

        # Timezone
        tz = timezone(getEnvVar(EnvVarName.TIMEZONE))
        if isEmpty(tz):
            raise RuntimeError("Missing required environment variable: " + EnvVarName.TIMEZONE.name)

        # Latitude
        latitude = getEnvVar(EnvVarName.LATITUDE)
        if isEmpty(latitude):
            raise RuntimeError("Missing required environment variable: " + EnvVarName.LATITUDE.name)

        # Longitude
        longitude = getEnvVar(EnvVarName.LONGITUDE)
        if isEmpty(longitude):
            raise RuntimeError("Missing required environment variable: " + EnvVarName.LONGITUDE.name)

        # Location
        location = getEnvVar(EnvVarName.LOCATION)
        if isEmpty(location):
            raise RuntimeError("Missing required environment variable: " + EnvVarName.LOCATION.name)

        self.location = LocationInfo(location, region, tz, latitude, longitude)
Esempio n. 22
0
    def add_darkness(ax, dat, from_time, to_time, color='lightgray'):

        # location
        city = LocationInfo("London", "England", "Europe/London", 51.5, -0.116)

        # find start
        date_start = datetime.datetime.strptime(dat[0][2], '%Y-%m-%d')
        s = sun(city.observer, date=date_start)

        for i, x in enumerate([d[0] for d in dat]):
            if datetime.datetime.strptime(
                    x, '%H:%M:%S').time() >= s[from_time].time():
                dusk = i
                break

        # find end
        date_end = datetime.datetime.strptime(dat[-1][2], '%Y-%m-%d')
        s = sun(city.observer, date=date_end)

        for i, x in list(enumerate([d[0] for d in dat]))[::-1]:
            if datetime.datetime.strptime(
                    x, '%H:%M:%S').time() <= s[to_time].time():
                dawn = i
                break

        # add to plot
        darkness = patches.Rectangle((dusk, minval - 3),
                                     dawn,
                                     abs(minval - 3) + max(1, maxval + 3),
                                     facecolor=color)
        ax.add_patch(darkness)
Esempio n. 23
0
    def getsunrise_sunset(self, latitude, longitude, sundt):
        LOGGER.debug("Latitude: {0}, Longitude: {1}".format(float(self.latitude), float(self.longitude)))

        l = LocationInfo('name', 'region', 'time/zone', latitude, longitude)
        s = sun(l.observer, sundt)
        sun_sr = self.utc_to_local(s["sunrise"], self.isdst)
        sun_ss = self.utc_to_local(s["sunset"], self.isdst)
        return sundt, sun_sr, sun_ss
Esempio n. 24
0
def _indexable_to_locationinfo(idxable) -> LocationInfo:
    return LocationInfo(
        name=idxable[0],
        region=idxable[1],
        timezone=idxable[2],
        latitude=dms_to_float(idxable[3], 90.0),
        longitude=dms_to_float(idxable[4], 180.0),
    )
Esempio n. 25
0
 def is_night():
     """ Check is it night now """
     location = LocationInfo(**LOCATION)
     datetime_now = datetime.now(tz=location.tzinfo)
     sun_info = sun(location.observer,
                    date=datetime_now.date(),
                    tzinfo=location.timezone)
     return not (sun_info['sunrise'] <= datetime_now < sun_info['sunset'])
Esempio n. 26
0
 def set_sunrise(self):
     loc = LocationInfo(name=self.name_it,
                        region='Italy',
                        timezone='Europe/Rome',
                        latitude=self.latitude,
                        longitude=self.longitude)
     s = sun(loc.observer, date=datetime.date.today())
     self._sunrise = s["sunrise"]
Esempio n. 27
0
 def info(self) -> LocationInfo:
     return LocationInfo(
         self.name,
         self.region,
         self.timezone,
         self.latitude,
         self.longitude,
     )
def test_Dawn_NeverReachesDepression():
    d = datetime.date(2016, 5, 29)
    with pytest.raises(ValueError):
        loc = Location(
            LocationInfo("Ghent", "Belgium", "Europe/Brussels", "51°3'N",
                         "3°44'W"))
        loc.solar_depression = 18
        loc.dawn(date=d, local=True)
Esempio n. 29
0
    def test_SolarDepression(self):
        c = Location(
            LocationInfo("Heidelberg", "Germany", "Europe/Berlin", 49.412,
                         -8.71))
        c.solar_depression = "nautical"
        assert c.solar_depression == 12

        c.solar_depression = 18
        assert c.solar_depression == 18
Esempio n. 30
0
def SetSunTimes():
    cityName = config.Get("cityName")
    if cityName != None:
        city = LocationInfo(cityName)
        s = sun(city.observer, date=datetime.now())
        variables.Set("dawn", str(s['dawn'].strftime("%H:%M")), True)
        variables.Set("sunrise", str(s['sunrise'].strftime("%H:%M")), True)
        variables.Set("sunset", str(s['sunset'].strftime("%H:%M")), True)
        variables.Set("dusk", str(s['dusk'].strftime("%H:%M")), True)