Beispiel #1
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')
Beispiel #2
0
def calculate_sunrise(year_to_simulate, longitude, latitude):
    """
    Calculate the hour of sunrise for a given year, longitude and latitude. Returns an array
    of hours.
    """

    # get the time zone name
    tf = TimezoneFinder()
    time_zone = tf.timezone_at(lng=longitude, lat=latitude)

    # define the city_name
    location = Location()
    location.name = 'name'
    location.region = 'region'
    location.latitude = latitude
    location.longitude = longitude
    location.timezone = time_zone
    location.elevation = 0

    sunrise = []
    for day in range(1, 366):  # Calculated according to NOAA website
        dt = datetime.datetime(year_to_simulate, 1, 1) + datetime.timedelta(day - 1)
        dt = pytz.timezone(time_zone).localize(dt)
        sun = location.sun(dt)
        sunrise.append(sun['sunrise'].hour)
    print('complete calculating sunrise')
    return sunrise
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)
Beispiel #4
0
def CalcAstralDayTime(Date,Time,Latitude,Longitude):
    """
    Calcule la position du soleil pour l'heure donnée.
    :param Date: Date UTC
    :param Time:  Heure UTC
    :param Latitude: Latitude
    :param Longitude: Longitude
    :return: D pour Day, U pour Dusk/crépuscule, N pour Night/Nuit, A pour Aube/Dawn
    """
    from astral import Location
    l = Location()
    l.solar_depression= 'nautical'
    l.latitude = Latitude
    l.longitude = Longitude
    s = l.sun(date=Date, local=False)
    # print(Date,Time,Latitude,Longitude,s,)
    Result = '?'
    Inter=( {'d': 'sunrise', 'f': 'sunset' , 'r': 'D'}
          , {'d': 'sunset' , 'f': 'dusk'   , 'r': 'U'}
          , {'d': 'dusk'   , 'f': 'dawn'   , 'r': 'N'}
          , {'d': 'dawn'   , 'f': 'sunrise', 'r': 'A'}
           )
    for I in Inter:
        if s[I['d']].time()<s[I['f']].time() and (Time>=s[I['d']].time() and Time<=s[I['f']].time() ) :
            Result=I['r']
        elif s[I['d']].time() > s[I['f']].time() and (Time >= s[I['d']].time() or Time <= s[I['f']].time()):
            Result = I['r'] # Changement de jour entre les 2 parties de l'intervalle
    return Result
Beispiel #5
0
def pozicija_sonca():
    """
    Pridobitev podatkov o času sončnega vzhoda in sončnega zahoda

    Astral modul:
    https://astral.readthedocs.io/en/stable/index.html
    """

    # Določitev lokacije
    l = Location()
    l.name = 'Grgar, Breg'
    l.region = 'Goriška'
    l.latitude = 45.999142
    l.longitude = 13.682394
    l.timezone = 'CET'
    l.elevation = 297  # 297m, 974.41feet
    sonce = l.sun()

    # Sončni vzhod
    soncni_vzhod = sonce['sunrise'].time()

    # Sončni zahod
    soncni_zahod = sonce['sunset'].time()

    return {'vzhod': soncni_vzhod, 'zahod': soncni_zahod}
Beispiel #6
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
Beispiel #7
0
 def is_day(self):
     l = Location()
     l.latitude = self.latitude
     l.longitude = self.longitude
     current_time = datetime.now(l.tzinfo)
     if (l.sunset() > current_time) and (l.sunrise() < current_time):
         return True
     else:
         return False
Beispiel #8
0
def get_location_astral(lat, lng, elev):
    loc = Location()
    loc.name = 'solar_tracker'
    loc.region = 'whereIam'
    loc.latitude = lat
    loc.longitude = lng
    loc.timezone = 'US/Mountain'
    loc.elevation = elev  # TODO: do we need this?
    logger.info('Astral location: [{}]'.format(loc))
    return loc
Beispiel #9
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
Beispiel #10
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.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.writeln('sunset {}:{}'.format(sunset_hour, sunset_minute))

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

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

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

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

        if sunrise_seconds < 0 and sunset_seconds <= 0:
            self.writeln("Turning on the lights")
            self.turnOn()
            self.writeln("Turning off the lights in {} seconds".format(
                -sunrise_seconds))
            return -sunrise_seconds
        elif sunrise_seconds > 0 and sunset_seconds > 0:
            self.writeln("Turning on the lights")
            self.turnOn()
            self.writeln(
                "Turning off the lights in {} seconds".format(sunrise_seconds))
            return sunrise_seconds
        elif sunrise_seconds <= 0 and sunset_seconds > 0:
            self.writeln("Turning off the lights")
            self.turnOff()
            self.writeln(
                "Turning on the lights in {} seconds".format(sunset_seconds))
            return sunset_seconds
Beispiel #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
def main(us_se):
    if 'location' not in us_se:
        logger.error('Invalid config file')
        return

    if us_se['location']['auto_enabled']:
        loc = get_loc_from_ip()
        if loc:
            loc = loc.json()
        else:
            logger.error('Couldn\'t connect to ipinfo, giving up')
            return

        loc['latitude'], loc['longitude'] = (
            float(x) for x in loc['loc'].strip().split(','))
        loc['time_zone'] = tzlocal.get_localzone().zone

    else:
        for k, v in us_se['location']['manual'].items():
            try:
                val = v.strip()
            except AttributeError:
                pass
            else:
                if not val:
                    logger.error(
                        'Auto location is not enabled and some manual values are missing'
                    )
                    return
        loc = us_se['location']['manual']

    try:
        location = Location()
        location.name = loc['city']
        location.region = loc['region']
        location.latitude = loc['latitude']
        location.longitude = loc['longitude']
        location.timezone = loc['time_zone']
    except ValueError as e:
        logger.error(str(e))
        return

    sunrise = location.sun()['sunrise'].replace(second=0) + timedelta(
        minutes=us_se['offset']['sunrise'])
    sunset = location.sun()['sunset'].replace(second=0) + timedelta(
        minutes=us_se['offset']['sunset'])

    #   Convert to UTC for storage
    return sunrise.astimezone(pytz.utc), sunset.astimezone(pytz.utc)
Beispiel #13
0
def get_kp84_sunrise_time(tnow):
    """give current time"""
    l = Location()
    l.name = 'KP84'
    l.region = 'Kitt Peak Observatory'
    l.latitude = 31.9599  # N
    l.longitude = -111.5997  # in east  (111.5997 w)
    l.timezone = "US/Arizona"
    l.elevation = 2099  # in meters
    if tnow.hour > 12:
        sun = l.sun(date=datetime.date(tnow.year, tnow.month, tnow.day) +
                    datetime.timedelta(days=1))
    else:
        sun = l.sun(date=datetime.date(tnow.year, tnow.month, tnow.day))
    tsunrise = sun['sunrise']
    return tsunrise
Beispiel #14
0
    def construct_astral_location(self, ) -> Location:
        """Return astral location object based on config."""
        # Initialize a custom location for astral, as it doesn't necessarily
        # include your current city of residence
        location = Location()

        # These two doesn't really matter
        location.name = 'CityNotImportant'
        location.region = 'RegionIsNotImportantEither'

        # But these are important, and should be provided by the user
        location.latitude = self.event_listener_config['latitude']
        location.longitude = self.event_listener_config['longitude']
        location.elevation = self.event_listener_config['elevation']
        location.timezone = 'UTC'

        return location
Beispiel #15
0
def get_sun_times(dt=datetime.datetime.now()):

    loc = Location()
    loc.name = 'Melbourne'
    loc.region = 'Oceania'
    loc.latitude = -37.787027
    loc.longitude = 145.110013
    loc.timezone = 'Australia/Melbourne'
    loc.elevation = 75

    loc.solar_depression = 'civil'

    resp = {}
    for k, v in loc.sun(dt).items():

        resp[k] = arrow.get(v).timestamp

    return resp
Beispiel #16
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)
Beispiel #17
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())
    def get_sun_info(datafile):

        site = Location()
        site.name = datafile.Site
        site.region = datafile.Country
        site.latitude = datafile.Latitude
        site.longitude = datafile.Longitude
        site.elevation = 0

        current_day = datafile.UtcStartTime.date()
        sun = site.sun(date=current_day)

        sunrise = sun['sunrise']
        sunset = sun['sunset']

        if sunset.date() > current_day:
            previous_day = current_day - timedelta(days=1)
            sun = site.sun(date=previous_day)
            sunset = sun['sunset']

        return sunrise, sunset
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
Beispiel #20
0
def main(us_se, logs=None):
    if us_se['location']['auto_enabled']:
        loc = get_loc_from_ip(logs)
        if loc:
            loc = loc.json()
        else:
            return 'ERROR: Couldn\'t connect to ipinfo, giving up', True

        loc['longitude'] = float(loc['loc'].strip().split(',')[1])
        loc['time_zone'] = tzlocal.get_localzone().zone
        loc['latitude'] = float(loc['loc'].strip().split(',')[0])

    else:
        for k, v in us_se['location']['manual'].items():
            try:
                val = v.strip()
            except AttributeError:
                pass
            else:
                if not val:
                    return 'ERROR: Auto location is not enabled and some manual values are missing', True
        loc = us_se['location']['manual']

    try:
        location = Location()
        location.name = loc['city']
        location.region = loc['region']
        location.latitude = loc['latitude']
        location.longitude = loc['longitude']
        location.timezone = loc['time_zone']
    except ValueError as e:
        return 'ERROR: ' + str(e), True

    sunrise = location.sun()['sunrise'].replace(second=0) + timedelta(
        minutes=us_se['offset']['sunrise'])
    sunset = location.sun()['sunset'].replace(second=0) + timedelta(
        minutes=us_se['offset']['sunset'])

    #   Convert to UTC for storage
    return [sunrise.astimezone(pytz.utc), sunset.astimezone(pytz.utc)], False
Beispiel #21
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
Beispiel #22
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 = 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

# Electric mobility, restriction that the sum <= 100
# Note, households with larger driving distances will receive EVs first
Beispiel #23
0
camera = PiCamera()
camera.resolution = '2592x1944'
camera.framerate = 1
#camera.awb_mode = 'off'
camera.iso = 800

# ser = serial.Serial("/dev/ttyACM0",9600)

camera.exposure_mode = 'off'

l = Location()

l.name = 'current'
l.region = 'region'
l.latitude = cfg['latitude']
l.longitude = cfg['longitude']
l.timezone = 'America/Chicago'
l.elevation = cfg['elevation']
l.sun()

record_count = 0

#### 1. Function definitions
#########################################

#### _) Networking

def make_request(url, req_type, data):
    r = ""
    if req_type == "post":
        r = requests.post(url, json=data, headers={"x-api-key": api_key, "content-type": "application/json"})
Beispiel #24
0
## Setup Astral

a = Astral()

###

#Raspberry Pi timelapse tutorial: https://www.raspberrypi.org/forums/viewtopic.php?t=72435
#Python-Crontab: http://stackabuse.com/scheduling-jobs-with-python-crontab/

### Define Location

l = Location()
l.name = settings.NAME
l.region = settings.REGION
l.latitude = settings.LATITUDE
l.longitude = settings.LONGITUDE
l.timezone = settings.TIMEZONE
l.elevation = settings.ELEVATION
l.sun()

utc = pytz.UTC

### Configure Cron

cron = CronTab(user='******')

sun = l.sun(date=datetime.date.today(), local=False)
#sun = l.sun(date=datetime.date(2018, 7, 4), local=True)
#print('Dawn:    %s' % str(sun['dawn']))
#print('Sunrise: %s' % str(sun['sunrise']))
#print('Noon:    %s' % str(sun['noon']))
    def do_PUT(self):
        logging.debug("-- PUT")
        length = int(self.headers["Content-Length"])
        path = self.translate_path(self.path)
        data_string = self.rfile.read(length)
        print(data_string)
        if "/toggle" in self.path:
            logging.debug("--- TOGGLE")
            self.send_response(200, "TOGGLE_OK")
            self.send_header("Content-type", "text/html")
            self.end_headers()
            if HTTPHandler.br > 0:
                HTTPHandler.br = 0
                self.disable_pwm()
                # disable wakeup if we are right in one...
                if self.isInWakeupsequence == True:
                    if HTTPHandler.wakeup_task is not None:
                        HTTPHandler.wakeup_task.cancel()
                        self.isInWakeupsequence = False
            else:
                HTTPHandler.br = 255
                self.enable_pwm()
                logging.debug(HTTPHandler.br)
            GPIO.set_PWM_dutycycle(PWM, HTTPHandler.br)

        if "/on" in self.path:
            logging.debug("DEPRECATED --- ON")
            self.send_response(200, "ON_OK")
            self.send_response(200, "OFF_OK")
            self.send_header("Content-type", "text/html")
            self.end_headers()
            HTTPHandler.br = 255
            logging.debug(HTTPHandler.br)
            self.enable_pwm()
            GPIO.set_PWM_dutycycle(PWM, HTTPHandler.br)
        if "/off" in path:
            logging.debug("DEPRECATED --- OFF")
            self.send_response(200, "OFF_OK")
            self.send_header("Content-type", "text/html")
            self.end_headers()
            self.wfile.write("")
            HTTPHandler.br = 0
            self.disable_pwm()
            GPIO.set_PWM_dutycycle(PWM, HTTPHandler.br)

        if "/incr" in path:
            logging.debug("--- INCR")
            self.send_response(200, "INCR_OK")
            self.send_header("Content-type", "text/html")
            self.end_headers()
            self.wfile.write("")
            HTTPHandler.br = min(HTTPHandler.br + 10, 255)
            GPIO.set_PWM_dutycycle(PWM, int(HTTPHandler.br))


#                if HTTPHandler.br > 5 and not self.pwm_is_enabled:
#			self.enable_pwm()
        if "/decr" in path:
            logging.debug("--- DECR")
            self.send_response(200, "INCR_OK")
            self.send_header("Content-type", "text/html")
            self.end_headers()
            self.wfile.write("")

            HTTPHandler.br = max(HTTPHandler.br - 10, 0)
            logging.debug(HTTPHandler.br)
            GPIO.set_PWM_dutycycle(PWM, int(HTTPHandler.br))
            if HTTPHandler.br < 0:
                self.disable_pwm()
        if "/wakeuptime" in path:
            logging.debug("--- New wakeup time: ")
            #parse json
            data = simplejson.loads(data_string)
            wakeup_time = data['time']
            wakeup_time = int(wakeup_time)
            #wakeup_time = parser.parse(wakeup_time
            print(datetime.now(utc))
            print(int(wakeup_time))
            now = int(time.time() * 1000)
            #dt = datetime.today()  # Get timezone naive now
            #now = int(dt.timestamp())
            #now = (datetime.now())
            #-datetime.fromtimestamp(0)).total_seconds()
            #datetime(1970,1,1)).total_seconds()
            print(int(now))
            logging.info("--- sheduling wakeup in ")

            t = int((wakeup_time - now) / 1000)
            print(t)
            logging.info(int(wakeup_time))
            logging.debug("killing old wakeups")
            if HTTPHandler.wakeup_task is not None:
                HTTPHandler.wakeup_task.cancel()
            HTTPHandler.wakeup_task = Timer(
                t - (LIGHT_START_BEFORE_ALARM_TIME * 60), self.startIncrLight)
            HTTPHandler.wakeup_task.start()
            self.send_response(200, 'WAKEUP_OK')
            self.send_header("Content-type", "text/html")
            self.end_headers()
            returntime = (str(int(wakeup_time)))
            print("returntime: ")
            print(returntime)
            self.wfile.write(returntime)

        if "/sunrise" in path:
            logging.debug("--- Wakeup set to Sunrise ---")
            self.send_response(200, 'SUNRISE_OK')
            self.send_header("Content-type", "text/html")
            self.end_headers()

            send_url = 'http://freegeoip.net/json'
            r = requests.get(send_url)
            j = json.loads(r.text)
            lat = j['latitude']
            lon = j['longitude']

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

            l = Location()
            l.name = 'name'
            l.region = 'region'
            l.latitude = lat
            l.longitude = lon
            l.timezone = j['time_zone']
            #TODO:
            l.elevation = 200
            l.sun()

            tomorrow = datetime.today() + timedelta(days=1)
            sun = l.sun(date=tomorrow, local=True)
            local_tz = pytz.timezone(j['time_zone'])

            wakeup_time = sun['sunrise']

            now = datetime.now(utc)
            t = wakeup_time - now
            logging.info("Wakeup at")
            logging.info(wakeup_time)
            logging.debug("killing old wakeups")
            if HTTPHandler.wakeup_task is not None:
                HTTPHandler.wakeup_task.cancel()
            HTTPHandler.wakeup_task = Timer(
                t.total_seconds() - (LIGHT_START_BEFORE_ALARM_TIME * 60),
                self.startIncrLight)
            HTTPHandler.wakeup_task.start()

            self.wfile.write("%f" % wakeup_time)
Beispiel #26
0
    def __init__(
        self,
        skip_over_exposed_images=DefaultSettings.skip_over_exposed_images,
        skip_dark_images=DefaultSettings.skip_dark_images,
        skip_images_without_natural_light=DefaultSettings.
        skip_images_without_natural_light,
        output_filename=DefaultSettings.output_filename,
        input_dir=DefaultSettings.input_dir,
        audio_file=DefaultSettings.audio_file,
        audio_start=DefaultSettings.audio_start,
        last_frame_freeze=DefaultSettings.last_frame_freeze,
        image_extension=DefaultSettings.image_extension,
        output_extension=DefaultSettings.output_extension,
        encoder=DefaultSettings.encoder,
        encoding_quality=DefaultSettings.encoding_quality,
        framerate=DefaultSettings.framerate,
        threads=DefaultSettings.threads,
        latitude=DefaultSettings.latitude,
        longitude=DefaultSettings.longitude,
        elevation=DefaultSettings.elevation,
        timezone=DefaultSettings.timezone,
        dawn_dusk_offset=DefaultSettings.dawn_dusk_offset,
        white_overexposed_threshold_percentage=DefaultSettings.
        white_overexposed_threshold_percentage,
    ):
        self.skip_over_exposed_images = skip_over_exposed_images
        self.skip_dark_images = skip_dark_images
        self.skip_images_without_natural_light = skip_images_without_natural_light

        self.output_filename = output_filename
        self.input_dir = input_dir

        self.audio_file = audio_file
        self.audio_start = audio_start
        self.last_frame_freeze = last_frame_freeze

        self.image_extension = image_extension
        self.output_extension = output_extension
        self.encoder = encoder
        self.encoding_quality = encoding_quality

        self.framerate = framerate
        self.threads = threads

        self.latitude = latitude
        self.longitude = longitude
        self.elevation = elevation
        self.timezone = timezone
        self.timezone = timezone

        l = Location(())
        l.longitude = self.longitude
        l.latitude = self.latitude
        l.elevation = self.elevation
        l.timezone = self.timezone
        self.location = l

        self.dawn_dusk_offset = dawn_dusk_offset

        self.white_overexposed_threshold_percentage = white_overexposed_threshold_percentage

        self.link_dir = tempfile.mkdtemp()
Beispiel #27
0
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 = 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)
# Use e.g. https://www.latlong.net/
from astral import Location

location = Location()
location.solar_depression = 'civil'
location.latitude = 51.46228743834423
location.longitude = 5.604832025576658
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

# Electric mobility, restriction that the sum <= 100
# Note, households with larger driving distances will receive EVs first
Beispiel #28
0
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

    elif now.hour < l.sun()['noon'].hour and time != 0:
Beispiel #29
0
import datetime

from astral import Location

from asylum import config
from asylum import create_sqlite3_connection

SCHEDULE_TASK_TIMEOUT = 60 * 30

loc = Location()
loc.latitude = float(config['LOCATION']['Latitude'])
loc.longitude = float(config['LOCATION']['Longitude'])


def calcHours(day):
    hours = {}

    sun = loc.sun(date=day)
    hours[1] = sun['dawn']
    hours[2] = sun['sunrise']
    hours[3] = sun['noon']
    hours[4] = sun['sunset']
    hours[5] = sun['dusk']
    hours[6] = datetime.datetime.combine(day, datetime.time())
    return hours


today = datetime.date.today()
todayHours = calcHours(today)
tommorowHours = calcHours(today + datetime.timedelta(days=1))
Beispiel #30
0
from astral import Astral, Location
from datetime import datetime, date, timedelta, tzinfo
import pytz
import helper


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

l = Location()
l.name = 'home'
l.region = 'Northern California'
l.latitude = 37.8195
l.longitude = -122.2523
l.timezone = 'US/Pacific'
l.elevation = 125


def sun_single_day(date):
	"""Returns tuple of datetime objects and numerical values for solar patterns on a single day"""

	sun = l.sun(date=date, local=True)
	sunrise = sun['sunrise']
	sunset = sun['sunset']
	day_length = str(sunset-sunrise)
	solar_noon = l.solar_noon(date=date, local=True)
	solar_zenith = l.solar_elevation(solar_noon.replace(tzinfo=None))

	return {'sunrise':sunrise, 'sunset': sunset, 'daylength': day_length, 'solar_noon': solar_noon, 'zenith': solar_zenith}

Beispiel #31
0
#     @classmethod
#     def run(date_time):
#         pass
def datetime_to_hours(date_time):
    return date_time.hour + date_time.minute / 60 + date_time.second / 3600


# astral = Astral()
# city = astral['Hanoi']
# print(city.timezone)

location = Location()
location.name = 'Phanthiet'
location.region = 'Middle'
location.latitude = 11
location.longitude = 108
location.timezone = 'Asia/Saigon'
location.elevation = 0
sun = location.sun()

print(sun['dawn'])
print(sun['sunrise'])
print(sun['sunset'])
print(sun['dusk'])
print(sun['noon'])
time_line = {
    'dawn': datetime_to_hours(sun['dawn']),
    'dusk': datetime_to_hours(sun['dusk']),
    'noon': datetime_to_hours(sun['noon']),
}
time_line.update({
Beispiel #32
0
def textual_information(data_parsed, geo_data, config):
    """
    Add textual information about current weather and
    astronomical conditions
    """

    def _shorten_full_location(full_location, city_only=False):

        def _count_runes(string):
            return len(string.encode('utf-16-le')) // 2

        words = full_location.split(",")

        output = words[0]
        if city_only:
            return output

        for word in words[1:]:
            if _count_runes(output + "," + word) > 50:
                return output
            output += "," + word

        return output
                

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

    output = []
    timezone = city.timezone

    datetime_day_start = datetime.datetime.now()\
            .replace(hour=0, minute=0, second=0, microsecond=0)
    sun = city.sun(date=datetime_day_start, local=True)

    format_line = "%c %C, %t, %h, %w, %P"
    current_condition = data_parsed['data']['current_condition'][0]
    query = {}
    weather_line = wttr_line.render_line(format_line, current_condition, query)
    output.append('Weather: %s' % weather_line)

    output.append('Timezone: %s' % timezone)

    tmp_output = []
    tmp_output.append('  Now:    %s'
                      % datetime.datetime.now(pytz.timezone(timezone)).strftime("%H:%M:%S%z"))
    tmp_output.append('Dawn:    %s'
                      % str(sun['dawn'].strftime("%H:%M:%S")))
    tmp_output.append('Sunrise: %s'
                      % str(sun['sunrise'].strftime("%H:%M:%S")))
    tmp_output.append('  Noon:   %s'
                      % str(sun['noon'].strftime("%H:%M:%S     ")))
    tmp_output.append('Sunset:  %s'
                      % str(sun['sunset'].strftime("%H:%M:%S")))
    tmp_output.append('Dusk:    %s'
                      % str(sun['dusk'].strftime("%H:%M:%S")))
    tmp_output = [
        re.sub("^([A-Za-z]*:)", lambda m: colorize(m.group(1), "2"), x)
        for x in tmp_output]

    output.append(
        "%20s" % tmp_output[0] \
        + " | %20s " % tmp_output[1] \
        + " | %20s" % tmp_output[2])
    output.append(
        "%20s" % tmp_output[3] \
        + " | %20s " % tmp_output[4] \
        + " | %20s" % tmp_output[5])

    city_only = False
    suffix = ""
    if "Simferopol" in timezone:
        city_only = True
        suffix = ", Крым"

    if config["full_address"]:
        output.append('Location: %s%s [%5.4f,%5.4f]' \
                % (
                    _shorten_full_location(config["full_address"], city_only=city_only),
                    suffix,
                    geo_data["latitude"],
                    geo_data["longitude"],
                ))

    output = [
        re.sub("^( *[A-Za-z]*:)", lambda m: colorize(m.group(1), "2"),
               re.sub("^( +[A-Za-z]*:)", lambda m: colorize(m.group(1), "2"),
                      re.sub(r"(\|)", lambda m: colorize(m.group(1), "2"), x)))
        for x in output]

    return "".join("%s\n" % x for x in output)