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)
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}
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 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')
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
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
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 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
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
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
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)
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 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
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'])) #print('Sunset: %s' % str(sun['sunset'])) #print('Dusk: %s' % str(sun['dusk']))
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()
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 fin_mean = [ ] #time for each moon sky observation interplate, used for moon angle h_beg = [] h_end = []
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)
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"}) elif req_type == "get": r = requests.get(url, json=data, headers={"x-api-key": api_key, "content-type": "application/json"})
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}
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: # Morning daytime = 0
#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 penetrationEV = 26 penetrationPHEV = 32
#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() def log_h(mode, sensor, need, now): log_h_file = open(r'/var/www/html/log_h.txt', 'a')