예제 #1
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
예제 #2
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}
예제 #3
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
예제 #4
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
예제 #5
0
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)
예제 #6
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
예제 #7
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
예제 #8
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
예제 #9
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
예제 #11
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
예제 #12
0
import datetime
import time
import os

from astral import Location

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

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

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

daytime = -1
changed = False

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

    if now.hour < l.sun()['dawn'].hour and time != 3:
        # Night
        daytime = 3
        changed = True
예제 #13
0
GPIO.setup(21, GPIO.OUT)  #fertilizers
pwm_fertilizers = GPIO.PWM(21, 1000)
GPIO.setup(20, GPIO.OUT)  #watering
pwm_watering = GPIO.PWM(20, 1000)

#set light_sensor
i2c = busio.I2C(board.SCL, board.SDA)
light_sensor = adafruit_tsl2561.TSL2561(i2c)

#set temperature_sensor
temp_sensor = W1ThermSensor()

#set time of sunrise and sunset
astr = Location()
astr.name = 'Saint-Petersburg'
astr.region = 'Saint-Petersburg'
astr.latitude = 60.0
astr.longitude = 30.0
astr.timezone = 'Europe/Moscow'
astr.elevation = 20


#set log
def tfl():
    return str(datetime.datetime.today())[:19]


def log_m(string):
    log_m_file = open(r'/var/www/html/log_m.txt', 'a')
    log_m_file.write(tfl() + ' ' + string + '\n')
    log_m_file.close()
예제 #14
0
def test_Location_Country():
    c = Location()
    assert c.region == 'England'
    c.region = 'Australia'
    assert c.region == 'Australia'
    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)
예제 #16
0
from astropy.time import Time
from astropy.io.fits.hdu.hdulist import HDUList
from datetime import date
from astral import Astral, Location
from astropy.time import Time
import astropy.units as u

# don't worry about iers
#from astropy.utils import iers
#iers.conf.auto_download = False
#iers.conf.auto_max_age = None

# Location, never changes
apl = Location()
apl.name = 'Apache Point Observatory'
apl.region = 'NM'
apl.latitude = 32.780208
apl.longitude = -105.819749
apl.timezone = 'US/Mountain'
apl.elevation = 2790

aplEL = EarthLocation(lon=apl.longitude * u.deg,
                      lat=apl.latitude * u.deg,
                      height=apl.elevation * u.m)


def moon_angle_var(fobj, ext):
    #getting RA and DEC
    sampling = fobj[0].header

    #FINDING INTERPLATE SKY TIME
예제 #17
0
print("Api key: " + api_key)

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 = ""
예제 #18
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}

예제 #19
0
import datetime
import time
import os

from astral import Location

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

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

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

daytime = -1
changed = False

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

    if now.hour < l.sun()['dawn'].hour and time != 3:
        # Night
        daytime = 3
        changed = True
예제 #20
0
# class BackgroundConfig:
#     @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']),
예제 #21
0
                    format='%(asctime)s:%(levelname)s:%(lineno)d:%(message)s')

## 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']))