コード例 #1
0
ファイル: astro.py プロジェクト: kdudkov/tiny-home-automation
    def compute(self):
        location = Location(('name', 'reg', self.lat, self.lon, 'Europe/Moscow', self.alt))

        # 15' sun bottom + 35' refraction
        alt = location.solar_elevation()
        daytime = 'day'
        daytime_ext = 'day'
        if -6 <= alt < -5. / 6:
            daytime = 'twilight'
            daytime_ext = 'civil_twilight'
        elif -12 <= alt < -6:
            daytime = 'night'
            daytime_ext = 'nautical_twilight'
        elif -18 <= alt < -12:
            daytime = 'night'
            daytime_ext = 'astro_twilight'
        elif alt < -18:
            daytime = 'night'
            daytime_ext = 'night'

        self.context.set_item_value('daytime', daytime)
        self.context.set_item_value('daytime_ext', daytime_ext)
        self.context.set_item_value('sun_alt', alt)
        self.context.set_item_value('sun_az', location.solar_azimuth())

        sun = location.sun()
        self.context.set_item_value('sunrise', sun['sunrise'])
        self.context.set_item_value('sunset', sun['sunset'])
        self.context.set_item_value('noon', sun['noon'])

        self.context.set_item_value('moon_phase', location.moon_phase())
コード例 #2
0
	def getSunTimes(self):
		a = Location()
		a.timezone = "Europe/Berlin"
		tz = pytz.timezone(a.timezone)
		sunData = a.sun()
		n = datetime.datetime.now()
		n = tz.localize(n)
コード例 #3
0
ファイル: riseset.py プロジェクト: advsig/avr
#!/usr/bin/env python

import datetime
from astral import Astral, Location
import pytz

def dt2min(dt):
    return dt.hour * 60 + dt.minute

loc = Location(("Santa Clara", "California", 37.21, -121.58, "US/Pacific", 22))
loc.solar_depression = 'civil'
oneday = datetime.timedelta(days=1)
soy = datetime.date(2016, 1, 1)
for  i in (range(1, 366)):
    sun = loc.sun(date=soy, local=True)
    print("{{ 0x{0:X}, 0x{1:X} }},".format(dt2min(sun['sunrise']), dt2min(sun['sunset'])))
    soy = soy + oneday
コード例 #4
0
class AstralPositions:
    def __init__(self,
                 lat,
                 lon,
                 panel_tilt=20,
                 session_id=None,
                 ip_or_url='192.168.15.7',
                 port=27017):
        # Date/wall time attributes
        if session_id == None:
            import uuid
            self.session_id = uuid.uuid1()
        self.a = Astral()
        self.timezone_string = 'US/Pacific'

        # Timezone from lat/lng
        tzfinder = timezonefinder.TimezoneFinder()
        self.tz = tzfinder.certain_timezone_at(lat=lat, lng=lon)
        self.location = Location(('Burlingame', 'Pacific West', lat, lon,
                                  self.timezone_string, 6.1))
        self.sun = self.location.sun(date=dt.datetime.today().date(),
                                     local=True)
        print(self.sun)

        # MongoDB Tracking
        self.mongo_client = MongoClient(ip_or_url, port)
        self.db = self.mongo_client.astral

        # Tilt of theoretical panel
        self.tilt = math.radians(panel_tilt)

    def get_now_local(self):
        now = dt.datetime.now()
        localtime = pytz.timezone(self.tz)
        now_local = localtime.localize(now)
        return now_local

    @staticmethod
    def perdelta(start, end, delta):
        curr = start
        while curr <= end:
            yield curr
            curr += delta

    def get_azimuth(self, dt_local=None):
        if dt_local == None:
            dt_local = self.get_now_local()
        angle = self.location.solar_azimuth(dt_local)
        return angle

    def get_altitude(self, dt_local=None):
        if dt_local == None:
            dt_local = self.get_now_local()
        angle = self.location.solar_elevation(dt_local)
        return angle

    def _angular_doc(self):
        datetime = self.get_now_local()
        alt = self.get_curr_altitude(datetime)
        az = self.get_curr_azimuth(datetime)
        doc = {
            "altitude": alt,
            "azimuth": az,
            "datetime": datetime,
            "sessionid": self.session_id
        }
        solar_angles = self.db.solar_angles
        _id = solar_angles.insert_one(doc).inserted_id

    def collect_angular_data(period=2):
        pass

    def get_azimuth_angles(self, start, end, frequency=60, continuous=True):
        td = dt.timedelta(seconds=frequency)
        # datetimes = [start + i*td for i in ]
        # delta = end-start
        datetimes = list(self.perdelta(start, end, td))
        angles = [self.get_azimuth(d) for d in datetimes]
        angles = pd.DataFrame({
            'Datetime Local': datetimes,
            'Angle (deg)': angles
        })
        # while datetime <= end:
        #     start
        if not continuous:
            pass
        return angles

    def get_altitude_angles(self, start, end, frequency=60, continuous=True):
        td = dt.timedelta(seconds=frequency)
        # datetimes = [start + i*td for i in ]
        datetimes = list(self.perdelta(start, end, td))
        angles = [self.get_altitude(d) for d in datetimes]
        angles = pd.DataFrame({
            'Datetime Local': datetimes,
            'Angle (deg)': angles
        })
        # while datetime <= end:
        #     start
        if not continuous:
            pass
        return angles

    def get_solar_angles(self, start, end):
        local_start = self.tz.localize(start)
        local_end = self.tz.localize(end)
        azimuth_df = self.get_azimuth_angles(start=local_start, end=local_end)
        altitude_df = self.get_altitude_angles(start=local_start,
                                               end=local_end)
        altitude_angles = altitude_df['Angle (deg)']
        azimuth_angles = azimuth_df['Angle (deg)']
        zenith_angles = altitude_angles.apply(lambda x: 90 - x)
        datetimes = altitude_df['Datetime Local']
        azimuth_angles_rad = azimuth_angles.map(math.radians)
        zenith_angles_rad = zenith_angles.map(math.radians)
        altitude_angles_rad = altitude_angles.map(math.radians)
        cos_correct_df = ap.get_cos_factors(azimuth_angles_rad,
                                            zenith_angles_rad)
        solar_angles_df = pd.DataFrame({
            'Azimuth (rad)': azimuth_angles_rad,
            'Altitude (rad)': altitude_angles_rad,
            'Datetime Local': datetimes
        })
        return solar_angles_df
コード例 #5
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:    %%{{NOW(%s)}}' % timezone)
    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('  Zenith: %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)
コード例 #6
0
#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"})
    print(r)
コード例 #7
0
    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)
コード例 #8
0
def test_Location_Sun():
    c = Location()
    c.sun()
コード例 #9
0
class Runner(object):
    def __init__(self,
                 target_ip,
                 bulb,
                 delta,
                 tz,
                 lat,
                 long,
                 location_name='Location',
                 region_name='Russia',
                 elevation=0,
                 color=((255, 255, 255), (225, 143, 0)),
                 brightness=(17, 50)):
        # ip address of target PC
        self.target_ip = target_ip
        # bulb attached to this pc
        self.bulb = bulb
        # check the current state
        self.__turned_on__ = self.turned_on

        # sunset offset percentage between dusk and sunset, when bulb is turn on
        self.delta = delta

        # color and brightness gradient for sunrise effect
        self.grad = [
            (int(c.red * 255), int(c.green * 255), int(c.blue * 255))
            for c in list(
                Color(rgb=(color[0][0] / 255, color[0][1] / 255,
                           color[0][2] / 255)).range_to(
                               Color(rgb=(color[1][0] / 255, color[1][1] / 255,
                                          color[1][2] / 255)), 30))
        ]
        self.brightness = range(*brightness) if brightness[1] > brightness[0] else \
            list(reversed(range(*list(reversed(brightness)))))

        # setup current location and timezone
        self.tz = pytz.timezone(tz)
        self.location = Location(
            (location_name, region_name, lat, long, tz, elevation))
        self.dusk = None
        self.sunrise = None
        self.sunset = None
        self.set_sun()

        # logging
        self.logger = logging.getLogger('yee')
        formatter = logging.Formatter('%(asctime)-15s %(message)s')
        fh = logging.FileHandler('yee.log')
        ch = logging.StreamHandler()

        ch.setFormatter(formatter)
        fh.setFormatter(formatter)

        self.logger.setLevel(logging.INFO)
        self.logger.addHandler(fh)
        self.logger.addHandler(ch)
        self.logger.info('START with current state: %s',
                         'on' if self.__turned_on__ else 'off')

    def toggle(self, state=None, retry=3):
        """
        toggle bulb power state
        :param state:
        :param retry:
        :return:
        """
        try:
            bulb = Bulb(self.bulb)
            if state is False:
                self.upd(0)
                bulb.turn_off()
                self.__turned_on__ = False
            elif state is True:
                bulb.turn_on()
                self.__turned_on__ = True
            else:
                bulb.toggle()
                self.__turned_on__ = not self.__turned_on__
        except BulbException:
            time.sleep(10)
            if retry > 0:
                return self.toggle(state, retry - 1)

    def upd(self, progress=None, retry=3):
        """
        update the current bulb colour and brightness
        :param progress:
        :param retry:
        :return:
        """
        try:
            _progress = progress or min(
                max((self.now - self.sunset).seconds, 0) /
                (self.dusk - self.sunset).seconds, 1)
            bulb = Bulb(self.bulb)
            bulb.set_rgb(*self.grad[min(int(_progress * len(self.grad)),
                                        len(self.grad) - 1)])
            bulb.set_brightness(self.brightness[min(
                int(_progress * len(self.brightness)),
                len(self.grad) - 1)])
        except BulbException:
            time.sleep(10)
            if retry > 0:
                return self.upd(progress, retry - 1)

    def get_state(self, retry=3):
        """
        get the current bulb state
        :return:
        """
        try:
            return Bulb(self.bulb).get_properties()['power']
        except BulbException:
            time.sleep(10)
            return self.get_state(retry - 1) if retry > 0 else None

    @property
    def turned_on(self):
        """
        check the current bulb power state
        :return:
        boolean
        """
        state = self.get_state()
        return self.__turned_on__ if (state is None) else state == 'on'

    @property
    def is_up(self):
        ret = subprocess.call(['ping', '-c', '5', '-W', '3', self.target_ip],
                              stdout=open('/dev/null', 'w'),
                              stderr=open('/dev/null', 'w'))
        return ret == 0

    @property
    def now(self):
        return self.tz.fromutc(datetime.utcnow())

    def check(self):
        now = self.now

        # sun is up - wait until next day
        if not self.sunset < now < self.sunrise:
            # turn off if it still up
            if self.turned_on:
                self.logger.info('turned OFF: %s', 'sunrise')
                self.toggle(False)
            # sleep until next sunset
            self.set_sun()
            delay = (self.sunset - now).seconds
            self.logger.info('sleep for : %s', delay)
            time.sleep(delay)
            return self.check()

        # pc is powered off - shut down bulb
        # check every minute
        if not self.is_up:
            if self.turned_on:
                self.logger.info('turned OFF: %s', 'pc is down')
                self.toggle(False)
            time.sleep(60)
            return self.check()

        # sun is down
        # pc is up
        # bulb should turned on
        # check every minute
        if not self.turned_on:
            self.logger.info('turned ON: %s', 'default state')
            self.toggle(True)

        # try to set colour AFTER turn the bulb on
        if self.sunset < now < self.dusk:
            self.upd()

        time.sleep(60)
        return self.check()

    def set_sun(self):
        """
        update data
        :return:
        """
        now = self.now
        i1, i2 = self.location.sun(now), self.location.sun(now + timedelta(1))
        self.dusk = i1['dusk']
        self.sunset = i1['sunset'] + timedelta(
            seconds=int((self.dusk - i1['sunset']).seconds * self.delta))
        self.sunrise = i2['sunrise']

    def run(self):
        self.check()
コード例 #10
0
 def _update_sun_info(self):
     location = Location(('name', 'region', float(self._latitude),
                          float(self._longitude), 'GMT+0', 0))
     self.sun = location.sun()
コード例 #11
0
ファイル: Hal9000_1_0.py プロジェクト: PGN55555/hal9000
        time.sleep(2)
        pwm_watering.stop()
        log_w('OK ', str(GPIO.input(17)))
        return date_today
    else:
        log_w('NT ', str(GPIO.input(17)))
        return last_watering


#main
indication(3)

while not flag_off:
    if date.today() != date_today:
        date_today = date.today()
        sun = astr.sun(date=datetime.date.today(), local=True)
        sunrise = str(sun['sunrise'])[11:16]
        sunrise = int(sunrise.replace(':', ''))
        sunset = str(sun['sunset'])[11:16]
        sunset = int(sunset.replace(':', ''))
        log_m('Sunrise = ' + str(sunrise) + '     sunset = ' + str(sunset))
    c_time = str(datetime.datetime.now())[11:16]
    c_time = int(c_time.replace(':', ''))

    flag_heating = heating()  #heating

    flag_lighting = lighting()  #lighting

    last_fertilizers = fertilizers()  #fertilizers

    last_watering = watering()  #watering
コード例 #12
0
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
        changed = True

    elif now.hour < l.sun()['sunset'].hour and time != 1:
        # Lunch
        daytime = 1
        changed = True

    elif now.hour < l.sun()['dusk'].hour and time != 2:
コード例 #13
0
import datetime, sys
from astral import Astral, Location
from datetime import date
lat = float(sys.argv[1])
lon = float(sys.argv[2])
zone = sys.argv[3]
l = Location(('wsprep', 'local', lat, lon, zone, 0))
l.sun()
d = date.today()
sun = l.sun(local=True, date=d)
print(str(sun['sunrise'])[11:16] + " " + str(sun['sunset'])[11:16])
コード例 #14
0
ファイル: background.py プロジェクト: JakobGM/dotfiles
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
        changed = True

    elif now.hour < l.sun()['sunset'].hour and time != 1:
        # Lunch
        daytime = 1
        changed = True

    elif now.hour < l.sun()['dusk'].hour and time != 2: