def main():
    loop = asyncio.get_event_loop()
    local_sun = Sun(config.LATITUDE, config.LONGITUDE)

    today_datetime = datetime.datetime.now(tz=pytz.utc)

    sunrise_datetime = local_sun.get_sunrise_time(today_datetime.date())
    sunset_datetime = local_sun.get_sunset_time(today_datetime.date())

    while True:

        # If sunrise has already passed, get the next sunrise
        if sunrise_datetime < today_datetime:
            sunrise_datetime = local_sun.get_sunrise_time(
                today_datetime.date() + datetime.timedelta(1))

        # If sunset is sooner than the sunrise
        if sunset_datetime < sunrise_datetime:
            print("Sunset is soonest, pausing")
            pause_until(sunset_datetime)
            # pause.until(sunset_datetime)
            loop.run_until_complete(led_on())
            sunset_datetime = local_sun.get_sunset_time(today_datetime.date() +
                                                        datetime.timedelta(1))
            # Launch wallpaper monitor here
        if sunrise_datetime < sunset_datetime:
            print("Sunrise is soonest, pausing")
            pause_until(sunrise_datetime)
            # pause.until(sunrise_datetime)
            loop.run_until_complete(led_off())
            sunrise_datetime = local_sun.get_sunset_time(
                today_datetime.date() + datetime.timedelta(1))
Esempio n. 2
0
def update_sun_times():
    try:
        sun = Sun(latitude, longitude)
        sunrise = sun.get_sunrise_time()
        sunset = sun.get_sunset_time()
        # Version for machine's local time
        # sunrise = sun.get_local_sunrise_time()
        # sunset = sun.get_local_sunset_time()
        light_turnOn = sunset + timedelta(minutes=20)
        light_turnOn_time = time(light_turnOn.hour,
                                 light_turnOn.minute,
                                 tzinfo=tz.tzutc())
        light_turnOff = sunrise + timedelta(minutes=30)
        light_turnOff_time = time(light_turnOff.hour,
                                  light_turnOff.minute,
                                  tzinfo=tz.tzutc())
        if (manualMode == True):
            if debug:
                print(
                    "=== Sun times acquired, switching to sunrise/sunset mode ==="
                )
            manualMode = False
        elif (manualMode == False):
            if debug:
                print("=== Sun times updated ===")
        return True
    except SunTimeException as e:
        if debug:
            print("SunTime failed. Error: {0}.".format(e))
            print("!!! SWITCHING TO MANUAL TIME MODE !!!")
        manualMode = True
        return False
 def change_mode(self):
     sun = Sun(self.latitude, self.longitude)
     sunrise = '''
                 tell application "System Events"
                     tell appearance preferences
                         set dark mode to false
                     end tell
                 end tell
                 '''
     sunset = '''
         tell application "System Events"
                     tell appearance preferences
                         set dark mode to true
                     end tell
                 end tell
     
     '''
     p = Popen(['osascript', '-'],
               stdin=PIPE,
               stdout=PIPE,
               stderr=PIPE,
               universal_newlines=True)
     today_sr = (sun.get_sunrise_time() -
                 datetime.timedelta(hours=16)).strftime('%Y-%m-%d %H:%M')
     today_ss = (sun.get_sunset_time() +
                 datetime.timedelta(hours=8)).strftime('%Y-%m-%d %H:%M')
     print(today_sr, today_ss)
     # 获取当前时间
     now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
     # 白天(不需要开暗黑模式)
     if today_sr < now < today_ss:
         p.communicate(sunrise)
     else:
         p.communicate(sunset)
     return
Esempio n. 4
0
class Suntime:
    # magic!
    OFFSET = timedelta(minutes=30)

    def __init__(self, location, logger):
        self.logger = logger
        self.sun = None
        if location is not None:
            self.sun = Sun(location[0], location[1])

    def sunset(self, cur_date):
        sunset = self.sun.get_sunset_time(cur_date)
        return sunset - Suntime.OFFSET

    def sunrise(self, cur_date):
        sunrise = self.sun.get_sunrise_time(cur_date)
        return sunrise + Suntime.OFFSET

    def is_night(self, cur_date):
        if self.sun is None:
            return False

        sunrise = self.sunrise(cur_date)
        sunset = self.sunset(cur_date)
        if sunrise > sunset:
            if sunset <= cur_date <= sunrise:
                return True
        else:
            if sunrise <= cur_date <= sunset:
                return True
Esempio n. 5
0
def get_suntimes(date, latitude=47.26, longitude=11.39):
    sun = Sun(latitude, longitude)

    # Get today's sunrise and sunset in UTC
    today_sr = sun.get_sunrise_time(date)
    today_ss = sun.get_sunset_time(date)
    return ({'sunrise': today_sr, 'sunset': today_ss})
Esempio n. 6
0
def main():
    print("LED Controller Starting...")

    GPIO.setmode(GPIO.BCM)
    GPIO.setwarnings(False)
    GPIO.setup(18, GPIO.OUT)
    GPIO.output(18, GPIO.HIGH)
    while True:

        sun = Sun(latitude, longitude)
        sunrise = sun.get_sunrise_time()
        sunset = sun.get_sunset_time()
        print(sunrise)
        print(sunset)

        t = datetime.now(timezone.utc)
        print(t)

        seven_am = datetime.now(timezone.utc).replace(hour=6,
                                                      minute=0,
                                                      second=0,
                                                      microsecond=0)
        if seven_am < t < sunset:
            print("Time is greater than sunrise but less than sunset")
            GPIO.output(18, GPIO.HIGH)
        else:
            print("Before Sunrise or after Sunset")
            GPIO.output(18, GPIO.LOW)

        time.sleep(60)
Esempio n. 7
0
def getSunsetTime(when=None):
    s = Sun(lat,lon)
    if when is None:
        when = datetime.datetime.now()
    sunsetToday = s.get_sunset_time(when)
    sunsetToday = sunsetToday + datetime.timedelta(days=1)# library has off by 1 day, unsure why ? ( known issue? )
    print(f'Next sunset at: {sunsetToday.strftime('%m/%d/%y %H:%M')}')
    return sunsetToday
Esempio n. 8
0
    def is_day(self):
        sun = Sun(self.lat, self.lng)
        sunrise, sunset = sun.get_sunrise_time(), sun.get_sunset_time()
        if sunset < sunrise:
            sunset += timedelta(days=1)

        now = datetime.now(timezone.utc)
        return (sunrise < now < sunset
                or sunrise < now + timedelta(days=1) < sunset
                or sunrise < now + timedelta(days=-1) < sunset)
Esempio n. 9
0
def generate_pv_output(dt: datetime) -> int:
    """Wrapper to generate PV output.
    This gets the sunrise/sunset times for a given location
    and then invokes the actual PV calculation if the given datetime is inbetween the two times.

    If the given datetime is not between sunrise and sunset, 0 is returned instead.
    """
    sun = Sun(LATITUDE, LONGITUDE)

    sunrise = sun.get_sunrise_time()
    sunset = sun.get_sunset_time()

    if not is_sunny(dt, sunrise, sunset):
        return 0

    return calculate_pv_output(dt, sunrise, sunset)
Esempio n. 10
0
    async def run_timed_events(self):
        await self.wait_until_ready()

        if len(self.settings.behaviors.timed) == 0:
            return

        latitude = float(os.getenv('LOCAL_LATITUDE'))
        longitude = float(os.getenv('LOCAL_LONGITUDE'))
        sun = Sun(latitude, longitude)

        while True:
            now = datetime.now()
            sunrise = utc_to_local(sun.get_sunrise_time()).replace(tzinfo=None)
            sunset = utc_to_local(sun.get_sunset_time()).replace(tzinfo=None)
            timed_events = []
            for t in self.settings.behaviors.timed:
                if t.type == 'daily':
                    target_time = now.replace(hour=t.time[0],
                                              minute=t.time[1],
                                              second=0)
                elif t.type == 'sunrise':
                    target_time = sunrise - timedelta(
                        seconds=t.minutes_before * 60)
                elif t.type == 'sunset':
                    target_time = sunset - timedelta(seconds=t.minutes_before *
                                                     60)
                while target_time < now:
                    target_time += timedelta(days=1)
                timed_events.append({'event': t, 'time': target_time})
            timed_events = sorted(timed_events, key=lambda k: k['time'])
            next_event = timed_events[0]
            channel_id = next_event['event'].channel
            program_idx = next_event[
                'event'].program_index if 'program_index' in next_event[
                    'event'] else 0
            time_until = next_event['time'] - now
            print('time until next event: {}'.format(time_until))
            await asyncio.sleep(time_until.seconds)
            await self.run_program(next_event['event'].program,
                                   data=None,
                                   channel=self.get_channel(channel_id),
                                   program_idx=program_idx)
            await asyncio.sleep(60)
Esempio n. 11
0
def sun_rise_set(latitude, longitude, abd, TZ="UTC"):
    sun = Sun(latitude, longitude)
    if (TZ == "UTC"):
        today_sr = sun.get_sunrise_time()
        today_ss = sun.get_sunset_time()
        if DBG:
            print(
                'Today at {2[0]}°{2[1]}\'{2[2]:2.2f}"N {2[3]}°{2[4]}\'{2[5]:2.2f}"E the sun raised at {0} and get down at {1} UTC'
                .format(today_sr.strftime('%H:%M:%S'),
                        today_ss.strftime('%H:%M:%S'),
                        coord(latitude, longitude)))
        return today_sr, today_ss
    else:
        abd_sr = sun.get_local_sunrise_time(abd)
        abd_ss = sun.get_local_sunset_time(abd)
        if DBG:
            print(
                'On {0} the sun at {2[0]}°{2[1]}\'{2[2]:2.2f}\"N {2[3]}°{2[4]}\'{2[5]:2.2f}\"E raised at {1} and get down at {3}.'
                .format(abd, abd_sr.strftime('%H:%M:%S'),
                        coord(latitude, longitude),
                        abd_ss.strftime('%H:%M:%S')))
        return abd_sr, abd_ss
Esempio n. 12
0
def index(lat, lng):
    obs = get_obs()
    closest = sorted(obs,
                     key=lambda o: calc_distance(float(o[0][
                         'lat']), float(o[0]['lon']), lat, lng))[0]
    stk = [x for x in obs if x[0]["stn_name"] == "ST KILDA HARBOUR - RMYS"]
    if len(stk):
        stk = {
            "wind_spd_kt": stk[0][1]["wind_spd"],
            "wind_dir": stk[0][1]["wind_dir"]
        }
    else:
        stk = {"wind_spd_kt": "", "wind_dir": ""}
    forecast = get_forecast()
    sun = Sun(lat, lng)
    sunr = sun.get_sunrise_time().timestamp()
    sund = sun.get_sunset_time().timestamp()
    return json.dumps({
        "closest": {
            "stn":
            closest[0]["description"],
            "wind_dir":
            closest[1]["wind_dir"],
            "wind_spd_kt":
            closest[1]["wind_spd"],
            "app_tmp":
            closest[1]["apparent_temp"],
            "rel_humidity":
            closest[1]["rel_humidity"],
            "ts":
            round(
                datetime.datetime.strptime(closest[1]["datetime"],
                                           "%Y-%m-%dT%H:%M:%S%z").timestamp()),
        },
        "srss": [round(sunr), round(sund)],
        "stk": stk,
        "forecast": forecast,
    })
Esempio n. 13
0
def get_timezone(latitude, longitude):
    #Get today sunrise and sunset
    sun = Sun(latitude, longitude)
    today_sr = int(sun.get_sunrise_time().strftime('%H'))
    today_ss = int(sun.get_sunset_time().strftime('%H'))

    #Get timezone
    tf = TimezoneFinder()
    timezone = tf.timezone_at(lng=longitude, lat=latitude) # returns 'Europe/Berlin'

    #Get time
    tz = pytz.timezone(timezone)
    timezone_now = int(datetime.datetime.now(tz).strftime('%H'))

    logging.info(str(timezone_now))
    logging.info(str(today_sr))
    logging.info(str(today_ss))

    if timezone_now > today_sr and timezone_now < today_ss:
        day = "Day"
    else:
        day = "Night"

    return day
Esempio n. 14
0
# Thanks to this S.O question: https://es.stackoverflow.com/questions/387503/importerror-cannot-import-name-sun-from-suntime/387572

# We need suntime module: pip3 install suntime

import datetime

# Import suntime:
from suntime import Sun, SunTimeException

# Define latitude and longitude:
latitud = 43.36
longitud = -8.41

# Sun instance
sun = Sun(latitud, longitud)

# Set today's sunrise
hoy_sr = sun.get_sunrise_time()

# Set today's sunset
hoy_ss = sun.get_sunset_time()

# Print with format
print('Hoy el sol en Galicia salió a las {} y baja a las {}'.format(
    hoy_sr.strftime('%H:%M'), hoy_ss.strftime('%H:%M')))

# Result:

# Hoy el sol en Galicia salió a las 06:03 y baja a las 19:01
Esempio n. 15
0
bomba = 23

# GPIO setup
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(bomba, GPIO.OUT)

# coordenadas Covilhã
latitude = 40.28
longitude = -7.50
utc = pytz.utc

sun = Sun(latitude, longitude)

nascerSol = sun.get_sunrise_time()
porSol = sun.get_sunset_time()

#horario de verao
now = datetime.now().replace(tzinfo=utc)
dia = now.day
mes = now.month
hoje = (mes, dia)
iniVerao = (3, 29)
fimVerao = (10, 25)

if iniVerao < hoje < fimVerao:
    nascerSol = nascerSol + timedelta(hours=1)
    porSol = porSol + timedelta(hours=1)

print("Agora: ", str(now))
print("Nascer hoje: ", str(nascerSol))
Esempio n. 16
0
import datetime
from suntime import Sun, SunTimeException

# Lyon
latitude = 45.75
longitude = 4.85

sun = Sun(latitude, longitude)

# Get today's sunrise and sunset in UTC
today_sr = sun.get_sunrise_time()
today_ss = sun.get_sunset_time()
print('Today at Lyon the sun raised at {} and get down at {} UTC'.format(
    today_sr.strftime('%H:%M'), today_ss.strftime('%H:%M')))

# On a special date in your machine's local time zone
abd = datetime.date(2020, 9, 25)
abd_sr = sun.get_local_sunrise_time(abd)
abd_ss = sun.get_local_sunset_time(abd)
print(
    'On {} the sun at Lyon raised at {} and get down at {}. local time'.format(
        abd, abd_sr.strftime('%H:%M'), abd_ss.strftime('%H:%M')))
Esempio n. 17
0
class SolarPower:
    def __init__(self):
        #Solar Array Data
        self.itemCode = "ALTS-200W-24P"
        self.solarPanelEfficiency = 0.1572  #Prosent
        self.solarPanelMinTemp = -40  # Celsius
        self.solarPanelMaxTemp = 80  # Celsius
        self.solarPanelPower = 4864  # W
        self.solarPanelArea = 32  # m^2
        self.powersqm = 153  #W/m^2

        # Constants
        self.solarIridiationConstant = 1367  #W/m^2
        self.solarPanelMaxCloudLoss = 0.30  # prosent
        self.lat = 63.42
        self.lon = 10.40
        self.city = "Trondheim"
        self.sun = Sun(self.lat, self.lon)

        #data
        self.weatherData = self.getWeatherDataFromFile()

        #Weather Data
        self.key = "8554bc4036b0ec568b136bbba124d344"
        self.url = f"https://api.openweathermap.org/data/2.5/weather?lat={self.lat}&lon={self.lon}&appid={self.key}"

    def getWeatherDataFromFile(self):
        #data = pd.read_csv("weatherHistoryHourly.csv", dtype={"dt": "int64", "clouds_all":"int64"}, parse_dates=["dt_iso"])
        data = pd.read_csv("newWeatherData.csv",
                           dtype={
                               "dt": "int64",
                               "clouds_all": "int64"
                           },
                           parse_dates=["dt_iso"])
        return data

    def getIridiationDataFromFile(self):
        irridiationData = pd.read_csv("solarIridiation.csv",
                                      dtype={"P": "float64"})
        return irridiationData

    def weatherCoefficient(self,
                           timestamp=None,
                           date=None,
                           row=None,
                           data=None):

        if timestamp != None:
            cloud_coverage = row = data.loc[data["dt"] == timestamp,
                                            "clouds_all"]
            cloudCoefficient = 1 - (self.solarPanelMaxCloudLoss *
                                    cloud_coverage / 100)

            return cloudCoefficient

        elif date != None:
            pass

        elif row != None:
            cloud_coverage = data["clouds_all"][row]
            cloudCoefficient = 1 - (self.solarPanelMaxCloudLoss *
                                    cloud_coverage / 100)

            return cloudCoefficient

        else:
            return 1

        return 1

    def irradiationCoefficient(self, timestamp=None, data=None):
        return 1

    def powerCalculationHour(self, timestamp=None, row=None, data=None):

        timestamp = data["dt"][row]
        sunRise = self.sun.get_sunrise_time(
            datetime.datetime.utcfromtimestamp(timestamp)).replace(tzinfo=None)
        sunSet = self.sun.get_sunset_time(
            datetime.datetime.utcfromtimestamp(timestamp)).replace(tzinfo=None)
        dataTime = datetime.datetime.utcfromtimestamp(timestamp)

        if sunRise < dataTime < sunSet:
            return self.solarIridiationConstant * self.solarPanelEfficiency * self.weatherCoefficient(
                row=row, data=data) * self.irradiationCoefficient()

        else:
            return 0

    def updateHistoricSolarPowerGeneration(self):
        data = self.getWeatherDataFromFile()
        data.loc[:, "generated_solar_power[Wh]"] = 0.1
        iri = self.getIridiationDataFromFile()

        for i in range(len(data["dt"]) - 1):
            timeC = datetime.datetime.utcfromtimestamp(
                data["dt"][i]).strftime("%m%d%H%M")
            series = iri.loc[iri["dateC"] == int(timeC), "P"]

            try:
                power = series.to_list()[0]
            except:
                timeC = datetime.datetime.utcfromtimestamp(
                    data["dt"][i - 1]).strftime("%m%d%H%M")
                series = iri.loc[iri["dateC"] == int(timeC), "P"]
                power = series.to_list()[0]

            data.loc[i,
                     "generated_solar_power[Wh]"] = power * self.solarPanelArea

        data.loc[:, "generated_solar_power[Wh]"].astype(float)
        """
       for i in range(len(data["dt"])):
           #data2["generated_solar_power[Wh]"][i] = self.powerCalculationHour(data["dt"][i])
           data.loc[:,"generated_solar_power[Wh]"].iloc[i] = self.powerCalculationHour(row = i, data=data)
           #print(f"{data['generated_solar_power[Wh]'][i]}  =   {self.powerCalculationHour(row = i)}")  
           
       """
        data.to_csv("newWeatherData.csv", index=False)

        return data

    def updateHistoricWeatherData(self):

        oldWeatherData = self.getWeatherDataFromFile()  # Get data
        lastOldDataTimestamp = oldWeatherData.loc[:, "dt"].iloc[
            len(oldWeatherData["dt"]) - 1] + 86400  # Last Timestamp
        lastOldDataDate = datetime.datetime.utcfromtimestamp(
            lastOldDataTimestamp)  # Last Timestamp in datetime format
        lastOldDataDay = lastOldDataDate.replace(hour=0)  # Last timestamp day

        currentDate = datetime.datetime.utcnow()
        currentDateTimestamp = int(currentDate.timestamp())

        deltatime = (currentDate - lastOldDataDay)

        df = df2 = pd.DataFrame(columns=oldWeatherData.columns)

        for days in range(deltatime.days):

            if (deltatime.days - days) < 5:
                timestamp = int(
                    (lastOldDataDay +
                     datetime.timedelta(days=days)).timestamp()) + 7200
                data = self.getHistoricWeatherDataFromTimestamp(timestamp)
                df2 = pd.DataFrame(
                    data["hourly"]).rename(columns={"clouds": "clouds_all"})

                df = df.append(df2).reset_index(drop=True)

            else:
                yesterdayTimestamp = int(
                    (lastOldDataDay + datetime.timedelta(days=deltatime.days) -
                     datetime.timedelta(days=1)).timestamp())
                data = self.getHistoricWeatherDataFromTimestamp(
                    yesterdayTimestamp)
                df2 = pd.DataFrame(
                    data["hourly"]).rename(columns={"clouds": "clouds_all"})

                timestamp = int((lastOldDataDay +
                                 datetime.timedelta(days=days)).timestamp() +
                                7200)
                #return lastOldDataDay
                for n in range(len(df2["dt"])):
                    df2["dt"][n] = timestamp + 3600 * n

                df = df.append(df2).reset_index(drop=True)

        df.loc[:, "dt"] = pd.to_numeric(df["dt"]).astype(int)

        for i in range(len(df["dt"])):

            df.loc[:, "dt_iso"].iloc[i] = str(
                datetime.datetime.utcfromtimestamp(df["dt"][i])) + " +0000 UTC"

        newWeatherData = oldWeatherData.append(df)
        newWeatherData.to_csv("newWeatherData.csv", index=False)

        return (df)

    def getHistoricWeatherDataFromTimestamp(self, timestamp):
        hUrl = f"http://api.openweathermap.org/data/2.5/onecall/timemachine?lat={self.lat}&lon={self.lon}&dt={timestamp}&appid={self.key}"
        get = requests.get(hUrl)
        hWeather = json.loads(get.content)

        return hWeather

    def getWeatherNow(self):

        get = requests.get(self.url)
        data = json.loads(get.content)

        return data

    def getSolarPowerNow(self):

        data = self.getWeatherNow()

        cloudFactor = data["clouds"]["all"] / 100
        sunRiseUnix = data["sys"]["sunrise"]
        sunSetUnix = data["sys"]["sunset"]

        systemSize = 6000  #W
        maxCloudLoss = 0.30  #prosent

        currentTimeUnix = time.time()
        if currentTimeUnix > sunRiseUnix and currentTimeUnix < sunSetUnix:
            return systemSize * (1 - maxCloudLoss * cloudFactor)

        else:
            return 0
Esempio n. 18
0
            nowTemp = dataControl.loc[hour, 'startTime']
            if nowTemp.hour == 22 or nowTemp.hour == 23:  # reduce ventilation when going to bed
                dataControl.loc[hour, 'ventilation'] = True
            if dataControl.loc[hour, 'waterTempIncrease']:
                dataControl.loc[hour, 'ventilation'] = False
                dataControl.loc[hour, 'compressor'] = True
                dataControl.loc[hour, 'addHeating'] = True

                # ensure that heating is allowed in initial programm start
        if initial:
            for hour in range(0, 2):
                dataControl.loc[hour, 'compressor'] = True
                dataControl.loc[hour, 'addHeating'] = True
                dataControl.loc[hour, 'ventilation'] = False
        sunrise = sun.get_sunrise_time() + dt.timedelta(hours=utcoffset)
        sunset = sun.get_sunset_time() + dt.timedelta(hours=utcoffset)
        
        # plot dashboard
        # gererate axis label for for weather data    
        timeVecWeather = []
        timeVecWeatherLabel = []
        timeVecWeatherMinor = []
        timeVecWeatherLabel = []
        for hour in range(0, len(weatherData)):
            a = weatherData.loc[hour, 'start_time']
            if a.hour == 0:
                timeVecWeather.append(hour)
                timeVecWeatherLabel.append(
                    ' ' + a.strftime('%a') + ' ' + a.strftime('%d') + '.' + a.strftime('%m') + '.')
            if (weatherData.loc[hour, 'start_time'].hour / 3).is_integer():
                timeVecWeatherMinor.append(hour)
Esempio n. 19
0
def get_sunset(address, from_grid=True):
    """Get sunset quality and parse into message"""

    # Load Sunburst API credentials
    EMAIL = os.getenv("SUNBURST_EMAIL")
    PASSWORD = os.getenv("SUNBURST_PW")
    url = "https://sunburst.sunsetwx.com/v1/login"

    # Get Sunburst API token via POST
    res = requests.post(url, auth=(EMAIL, PASSWORD))

    # res = requests.post(url, data=payload)
    result = re.findall(r'token\":\"[0-9a-xA-Z-]*', res.text)
    token = "Bearer " + result[0][8:]

    # Get sunset quality via Sunburst GET
    headers = {"Authorization": token}
    url = "https://sunburst.sunsetwx.com/v1/quality"

    # Return if invalid coords
    coords = address_to_coord(address)
    if coords == -1:
        return "Invalid location. Please enter valid address."

    total = 0

    # Get coordinates and quality at each coord
    coords_list = []

    # If calculate quality from grid, false if calculate from single coord
    if from_grid:
        coords_list = generate_grid(coords)
        if len(coords_list) == 0:
            coords_list = [str(coords[0]) + "," + str(coords[1])]
        else:
            coords_list = [str(coords[0]) + "," + str(coords[1])]

    for coord in coords_list:
        data = {"geo": coord}
        res = requests.get(url, headers=headers, params=data)
        try:
            quality_percent = re.findall(r'quality_percent\":\d*\.\d*',
                                         res.text)[0][17:]
        except:
            return "Too many Sunburst requests. Try again later."

        total += float(quality_percent)

    quality_percent = total / float(len(coords_list))
    quality = ""

    if quality_percent < 25:
        quality = "Poor"
    elif quality_percent < 50:
        quality = "Fair"
    elif quality_percent < 75:
        quality = "Good"
    else:
        quality = "Great"

    # Get today's sunset in local time
    sun = Sun(coords[0], coords[1])
    today_ss = sun.get_sunset_time()

    # Convert time zone
    GEO_USERNAME = os.getenv("GEONAMES_USERNAME")
    geolocator = GeoNames(username=GEO_USERNAME)
    timezone = geolocator.reverse_timezone(coords)
    from_zone = tz.gettz("UTC")
    to_zone = tz.gettz(str(timezone))
    today_ss = today_ss.replace(tzinfo=from_zone)
    sunset_time = today_ss.astimezone(to_zone)

    # Get day of week
    day_list = [
        "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
        "Sunday"
    ]
    day = day_list[datetime.datetime.today().weekday()]

    # Create message
    message = "Quality: " + quality + " " + str(round(
        quality_percent, 2)) + "%\nSunset at {}pm".format(
            sunset_time.strftime("%H:%M")) + "\n\n" + day + " at " + address

    return message
Esempio n. 20
0
config.read('/home/pi/coop/coop.ini')

# logging
logging.basicConfig(filename=config['Settings']['LogFile'],
                    level=config['Settings']['LogLevel'],
                    format='%(asctime)s - %(levelname)s: %(message)s')

# Suntime
sun = Sun(float(config['Location']['Latitude']),
          float(config['Location']['Longitude']))
now = (datetime.now(timezone.utc))
offset = int(config['Door']['Offset'])
doortime_open: int = int(config['Door']['Doortime_Open'])
doortime_close: int = int(config['Door']['Doortime_Close'])
opentime = sun.get_sunrise_time() - timedelta(minutes=offset)
closetime = sun.get_sunset_time() + timedelta(minutes=offset)
opentimetomorrow = sun.get_local_sunrise_time(datetime.now() +
                                              timedelta(days=1) -
                                              timedelta(minutes=offset))
closetimeyesterday = sun.get_local_sunset_time(datetime.now() + timedelta(
    days=-1)) + timedelta(minutes=offset)
global stop_threads

# GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
TopSensor = int(config['GPIO']['TopSensor'])
BottomSensor = int(config['GPIO']['BottomSensor'])
GPIO.setup(TopSensor, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(BottomSensor, GPIO.IN, pull_up_down=GPIO.PUD_UP)
MotorUp = int(config['GPIO']['IN3'])
Esempio n. 21
0
        'AppsUseLightTheme', '/t', 'REG_DWORD', '/d', values[1], '/f'
    ]
    windows = base + [
        'WindowsUseLightTheme', '/t', 'REG_DWORD', '/d', values[2], '/f'
    ]

    subprocess.run(system, stdout=subprocess.DEVNULL)
    subprocess.run(apps, stdout=subprocess.DEVNULL)
    subprocess.run(windows, stdout=subprocess.DEVNULL)


if __name__ == '__main__':
    # prepare for theme
    sun = Sun(45.4, 9.1)
    sunrise = sun.get_sunrise_time().strftime('%H:%M:%S')
    sunset = sun.get_sunset_time().strftime('%H:%M:%S')
    do_light, do_dark = True, True

    theme = {"light": ['1', '1', '0'], "dark": ['0', '0', '0']}

    # prepare for wallpapers
    path = r'{}\WallpaperEnhancer\Wallpapers'.format(os.environ['USERPROFILE'])
    files = os.listdir(path)
    images_str = [x.replace('.jpeg', '') for x in files]
    images = [int(x) for x in images_str]

    diff = [abs(x - int(get_time())) for x in images]
    first = str(images[diff.index(min(diff))])
    if len(first) == 5:
        first = '0' + first
Esempio n. 22
0
    def __call__(self, i):
        self.sysStats = updateSysStats(self.sysStats)
        sysStatsX = extractSysStats(self.sysStats, 'time')
        #CPU percentage
        self.ax1.cla()
        self.ax1.update(self.ax1props)
        cpuPercent = extractSysStats(self.sysStats, 'cpuPercent')
        cpuColors = ['y', 'b', 'g', 'm']
        for idx, color in zip(range(4), cpuColors):
            self.ax1.bar(sysStatsX,
                         cpuPercent[idx],
                         width=2,
                         zs=idx,
                         zdir='y',
                         color=color * len(sysStatsX),
                         alpha=.8)
        #CPU temperature
        cpuTempCel = extractSysStats(self.sysStats, 'cpuTempCel')
        self.lines[1]['cpuTempCel'].set_data(sysStatsX, cpuTempCel)
        #memory percertange
        memPercent = extractSysStats(self.sysStats, 'memPercent')
        self.lines[1]['memPercent'].set_data(sysStatsX, memPercent)
        #globe
        if max(self.sysStats.keys()) > self.ax4TimeToUpdate:
            if max(self.sysStats.keys()) > self.ax4TimeToGeoLoc:
                try:
                    geolocResponse = self.http.request(
                        'GET', 'http://ipinfo.io/json')
                    geolocData = json.loads(geolocResponse.data)
                    self.ax4GeoLoc = eval(geolocData['loc'])[0:2]
                except:
                    self.ax4GeoLoc = self.ax4GeoLoc

            self.ax4.cla()
            self.ax4.set_global()
            self.ax4.coastlines()
            #             self.ax4.stock_img()
            #             self.ax4.background_img(name='BM', resolution='low')
            utcnow = datetime.utcnow()
            self.ax4.add_feature(Nightshade(utcnow, alpha=.15))
            scatterLongitudes = [x[1] for x in CitiesCoords.values()
                                 ]  #+[self.ax4GeoLoc[1]]
            scatterLatitudes = [x[0] for x in CitiesCoords.values()
                                ]  #+[self.ax4GeoLoc[0]]
            scatterColors = ['c'] * len(CitiesCoords)  #+['r']
            self.ax4.scatter(scatterLongitudes,
                             scatterLatitudes,
                             s=10,
                             c=scatterColors,
                             alpha=.8,
                             transform=ccrs.PlateCarree())
            self.ax4.gridlines(crs=ccrs.PlateCarree(),
                               xlocs=[self.ax4GeoLoc[1]],
                               ylocs=[self.ax4GeoLoc[0]],
                               color='y',
                               alpha=.4)
            self.ax4.plot([self.ax4GeoLoc[1]], [self.ax4GeoLoc[0]],
                          ms=7,
                          c='r',
                          transform=ccrs.PlateCarree(),
                          **{
                              'marker': '$\\bigoplus$',
                              'linestyle': '',
                              'markeredgewidth': .1
                          })
            for (k, v) in CitiesCoords.items():
                self.ax4.text(v[1] + 3,
                              v[0] - 3,
                              k,
                              fontsize='xx-small',
                              color='b',
                              alpha=.95,
                              horizontalalignment='left',
                              verticalalignment='top',
                              transform=ccrs.Geodetic())
            sun = Sun(self.ax4GeoLoc[0], self.ax4GeoLoc[1])
            today = utcnow.date()
            sunrises = [
                sun.get_sunrise_time(d) for d in
                [today - timedelta(days=1), today, today + timedelta(days=1)]
            ]
            sunsets = [
                sun.get_sunset_time(d) for d in
                [today - timedelta(days=1), today, today + timedelta(days=1)]
            ]
            sunTimes = sunrises + sunsets
            sunTimes = [d.replace(tzinfo=None) for d in sunTimes]
            sunTimes.sort()
            sunTimeLast = [
                t for t in sunTimes if t < utcnow.replace(tzinfo=None)
            ][-1]
            sunTimeNext = [
                t for t in sunTimes if t >= utcnow.replace(tzinfo=None)
            ][0]
            sunHoursDeltas = [t - utcnow for t in [sunTimeLast, sunTimeNext]]
            sunHours = [
                td.days * 24 + td.seconds / 3600 for td in sunHoursDeltas
            ]
            sunHHMMs = [
                '{:+03.0f}:{:02.0f}'.format(math.trunc(sh),
                                            60 * abs(sh - math.trunc(sh)))
                for sh in sunHours
            ]
            meStrTxts = [
                self.ax4.text(self.ax4GeoLoc[1] + txtPosShiftHor,
                              self.ax4GeoLoc[0] + 3,
                              meStr,
                              fontsize='xx-small',
                              fontweight='normal',
                              color='m',
                              alpha=.99,
                              horizontalalignment=txtPosAlignHor,
                              transform=ccrs.Geodetic())
                for (meStr, txtPosAlignHor, txtPosShiftHor
                     ) in zip(sunHHMMs, ['right', 'left'], [-3, 3])
            ]
            for txtObj in meStrTxts:
                txtObj.set_path_effects(
                    [PathEffects.withStroke(linewidth=2, foreground='w')])
            self.ax4TimeToUpdate += timedelta(seconds=300)
            self.ax4TimeToGeoLoc += timedelta(seconds=1200)
Esempio n. 23
0
        line = f.readline()
        try:
            last = datetime.fromisoformat(line)
        except:
            print(
                'The last execution date is an invalid value. Delete the `.last` file.'
            )
            exit(1)

        if now.date() == last.date():
            # Do nothing
            exit(0)

try:
    sun = Sun(args.latitude, args.longitude)
    sunset = sun.get_sunset_time()
except:
    print('Uncalculated latitude and longitude.')
    exit(1)

if args.add:
    try:
        add_timedelta = timedelta(minutes=args.add)
    except:
        print('Uncalculated additional time.')
        exit(1)
    sunset += add_timedelta

if now < sunset:
    # Do nothing
    exit(0)
Esempio n. 24
0
def get_sunlight_data(bbox,
                      center=DEFAULT_COORDS,
                      start_time='2016-09-28',
                      end_time='2019-09-28'):

    sun = Sun(center[1], center[0])

    for cc in range(0, 11, 1):
        wms_true_color_request = WmsRequest(
            layer='TRUE_COLOR',
            bbox=bbox,
            width=1000,
            height=1000,
            time=(start_time, end_time),
            maxcc=cc / 10,
            instance_id='0d1f2199-b4b9-4bad-b88b-8b2423e57b93')

        data = wms_true_color_request.get_dates()

        for date in data:
            sunrise = sun.get_sunrise_time(date)
            sunset = sun.get_sunset_time(date)

            suntime = (sunset - sunrise)
            suntime_hour = (sunset.hour - sunrise.hour)
            suntime_minute = (sunset.minute - sunrise.minute)

            sunrise_f = "%02d:%02d" % (sunrise.hour, sunrise.minute)
            sunset_f = "%02d:%02d" % (sunset.hour, sunset.minute)

            # print(sunrise_f)
            # print(sunset_f)
            suntime_number_uf = (int(suntime_hour) +
                                 round(int(suntime_minute) / 60, 2))
            suntime_number_f = '{:0>5.02f}'.format(suntime_number_uf)

            #print("number: ", suntime_number_uf)
            pw = ((suntime_number_uf * 0.2 * 1) +
                  (suntime_number_uf * 0.2 * 0.7) +
                  (suntime_number_uf * 0.3 * 0.4) +
                  (suntime_number_uf * 0.3 * 0.2)) * 1000

            real_cc = cc / 10
            if (real_cc < 0.31):
                kwh = pw * 1
            elif (real_cc >= 0.31 and real_cc < 0.71):
                kwh = pw * 0.6
            elif (real_cc >= 0.71 and real_cc < 0.91):
                kwh = pw * 0.3
            elif (real_cc >= 0.91):
                kwh = pw * 0.1

            sunlight_data.append([
                date, sunrise_f, sunset_f,
                "%d%%" % (cc * 10), suntime, suntime_number_f,
                round(pw),
                round(kwh)
            ])

    # print(sunlight_data)
    return remove_duplicates(sunlight_data)
Esempio n. 25
0
#Getting the position of yesterday's date on the calender
dt = datetime.datetime.now()- datetime.timedelta(days=1)

#print(str(datetime.datetime.now()))

year = dt.year
month = dt.month
day = dt.day
hour = dt.hour

#Checking if it is day or night
latitude = 36.3504
longitude = 127.3845
sun = Sun(latitude, longitude)
sr_time = (sun.get_sunrise_time()+datetime.timedelta(hours=9)).time()
ss_time = (sun.get_sunset_time()+datetime.timedelta(hours=9)).time()
sr_hour = int(sr_time.hour)
ss_hour = int(ss_time.hour)
curr_time = datetime.datetime.now().time()
isDay = 0
if (sr_time < curr_time < ss_time):
    isDay = 1

#retrieving data
dict_param = {
    'yy': year,
    'mm': month,
    'dd': day,
    'hh': hour,
    'obs': 0
}
Esempio n. 26
0
    def sun_time(self):

        sun_time = Sun(self.latlon_point.latitude, self.latlon_point.longitude)

        self.date = self.date + timedelta(days=self.date_increase)

        try:
            today_sunrise = sun_time.get_sunrise_time(self.date)
        except SunTimeException:
            if date(year=self.date.year, month=3, day=21)\
                    < self.date.date()\
                    < date(year=self.date.year, month=9, day=22):
                return 0, 360
            return 0, 0

        try:
            today_sunset = sun_time.get_sunset_time(self.date)
        except SunTimeException:
            if date(year=self.date.year, month=3, day=21)\
                    < self.date.date()\
                    < date(year=self.date.year, month=9, day=22):
                return 0, 360
            return 0, 0

        # This is *super* ugly, I'm sure we can find a more elegant way to do this
        now = datetime.utcnow() - timedelta(hours=0)
        today_sunrise = today_sunrise.replace(tzinfo=None)
        today_sunset = today_sunset.replace(tzinfo=None)

        # After Sunrise, after Sunset
        if now > today_sunrise and today_sunset:
            # Get timedelta for each
            today_sunrise = now - today_sunrise
            today_sunset = now - today_sunset

            # Convert timedelta into minutes and round
            today_sunrise = round(today_sunrise.seconds / 60)
            today_sunset = round(today_sunset.seconds / 60)

            # Convert minutes into angles
            today_sunrise = today_sunrise * 0.25
            today_sunset = today_sunset * 0.25

        # Before Sunrise, after Sunset
        elif now < today_sunrise and today_sunset:
            today_sunrise = today_sunrise - now
            today_sunset = today_sunset - now

            today_sunrise = round(today_sunrise.seconds / 60)
            today_sunset = round(today_sunset.seconds / 60)

            today_sunrise = 360 - (today_sunrise * 0.25)
            today_sunset = 360 - (today_sunset * 0.25)

        # After Sunrise, before Sunset
        else:
            today_sunrise = now - today_sunrise
            today_sunset = today_sunset - now

            today_sunrise = round(today_sunrise.seconds / 60)
            today_sunset = round(today_sunset.seconds / 60)

            today_sunrise = today_sunrise * 0.25
            today_sunset = 360 - (today_sunset * 0.25)

        return today_sunrise, today_sunset
    ind_array = np.concatenate((ind_array, [len(np_cast) - 1]), axis=0)

    # calculating the sunrise and sunset times for each cast (if possible)
    # If the lattitudes are in the far north or south during summer/winter
    # There are no sunrise or sunset as it will all be day or night
    # All the times are in UTC
    k = 0
    for j in range(len(ind_array) - 1):

        d = date(np_year[ind_array[j]], np_month[ind_array[j]],
                 np_day[ind_array[j]])
        sun = Sun(np_lat[ind_array[j]], np_long[ind_array[j]])

        try:
            sr = sun.get_sunrise_time(d)
            ss = sun.get_sunset_time(d)

        except:
            # Any operation here is needed for the try method
            k += 1

        else:
            # IF the sunrise can be calculated, then we use the suntime module
            # to compute the sunrise and sunset times for each cast
            sr = sun.get_sunrise_time(d)
            ss = sun.get_sunset_time(d)
            np_sr[ind_array[j]:ind_array[j + 1]] = round(
                sr.hour + sr.minute / 60, 2)
            np_ss[ind_array[j]:ind_array[j + 1]] = round(
                ss.hour + ss.minute / 60, 2)
            j_arr[j] = (ind_array[j], ind_array[j + 1])
Esempio n. 28
0
import datetime
from suntime import Sun, SunTimeException
from datetime import datetime
from dateutil import tz

# Auto-detect timezones
from_zone = tz.tzutc()
to_zone = tz.tzlocal()

# Felton, CA 37.0513° N, 122.0733° W
city_name = "Felton, CA"
latitude = 37.0513
longitude = -122.0733

sun = Sun(latitude, longitude)

# Get today's sunrise and sunset in UTC
today_sr_utc = sun.get_sunrise_time()
today_sr_local = sun.get_local_sunrise_time()
today_ss_utc = sun.get_sunset_time()
today_ss_local = sun.get_local_sunset_time()

print('Today at {} the sun rose at {} and goes down at {} UTC'.format(
    city_name, today_sr_utc.strftime('%H:%M'), today_ss_utc.strftime('%H:%M')))
print('Today at {} the sun rose at {} and goes down at {} localtime'.format(
    city_name, today_sr_local.strftime('%H:%M'),
    today_ss_local.strftime('%H:%M')))