Ejemplo n.º 1
0
 def __init__(self, geocoder):
     self.local_time = LocalTime(geocoder)
     self.sun = Sun(geocoder)
     self.artwork = Artwork()
     self.city = City(geocoder)
     self.commute = Commute(geocoder)
     self.calendar = GoogleCalendar(geocoder)
     self.everyone = Everyone(geocoder)
Ejemplo n.º 2
0
def calc_sunrise(lat, lon, doy, date):
    date = date.replace(hour=0)
    sun = Sun()
    coords = {'longitude': lon, 'latitude': lat}
    sunr_dec = sun.getSunriseTime(coords, date=date)['decimal']
    suns_dec = sun.getSunsetTime(coords, date=date)['decimal']
    sunr_dec *= 60
    suns_dec *= 60
    sunrise = date + pd.to_timedelta(sunr_dec, unit='m')
    sunset = date + pd.to_timedelta(suns_dec, unit='m')
    return sunrise, sunset
Ejemplo n.º 3
0
    def __init__(self, geocoder):
        """Schedule constructor.

        Args:
            geocoder (geocoder.Geocoder): Used to localize user specified locations
        """
        self._local_time = LocalTime(geocoder)
        self._sun = Sun(geocoder)
        self._artwork = Artwork()
        self._city = City(geocoder)
        self._commute = Commute(geocoder)
        self._calendar = GoogleCalendar(geocoder)
        self._everyone = Everyone(geocoder)
Ejemplo n.º 4
0
    def load(self):
        settings = sublime.load_settings(PACKAGE + '.sublime-settings')
        settings.clear_on_change(PACKAGE)
        settings.add_on_change(PACKAGE, self.load)

        if not settings.has('day'):
            raise KeyError('SunCycle: missing day setting')

        if not settings.has('night'):
            raise KeyError('SunCycle: missing night setting')

        self.day = settings.get('day')
        self.night = settings.get('night')

        self.coordinates = {'latitude': settings.get('latitude', 0), 'longitude': settings.get('longitude', 0)}
        self.sun = Sun(self.coordinates)

        if self.coordinates['latitude'] != 0 or self.coordinates['longitude'] != 0:
            self.hardcodedLocation = True

        now = datetime.now(tz=self.getTimeZone())
        logToConsole('Sunrise at {0}'.format(self.sun.sunrise(now)))
        logToConsole('Sunset at {0}'.format(self.sun.sunset(now)))

        if self.loaded and self.onChange:
            self.onChange()

        self.loaded = True
    def do_GET(self):
        try:
            path_split = self.path.split('?')

            if (len(path_split) > 1) and (path_split[0] == '/LEDS'):
                specifiers = path_split[1].split('+')

                for specifier in specifiers:
                    key, value = specifier.split('=')
                    if key == 'on':
                        brightness = 0.5 if value == 'true' else 0.0
                        light.set_brightness(brightness)
                    elif key == 'brightness':
                        brightness = float(value)
                        light.set_brightness(brightness)
                    elif key == 'temperature':
                        temperature = float(value)
                        r, g, b = Sun.kelvin_to_rgb(temperature)
                        light.fill(r, g, b)
                    elif key == 'duotone':
                        r1, g1, b1, r2, g2, b2, seg = value.split(',')
                        light.duotone((r1, g1, b1), (r2, g2, b2), int(seg))
                    elif key == 'r':
                        light.set_r(float(value))
                    elif key == 'g':
                        light.set_g(float(value))
                    elif key == 'b':
                        light.set_b(float(value))

            print(self.path)
            self.send_http()

        except BrokenPipeError:
            pass
Ejemplo n.º 6
0
    def update(self):
        # state가 STATE_NEW이면 마우스 따라다니도록한다.
        if self.state == STATE_MOUNT:
            self.event_start += gfw.delta_time
            self.collisiontime += gfw.delta_time
            if self.event_start > self.event_time:
                if self.name != 'CherryBomb':
                    self.event_start = 0
                if self.name == 'SunFlower':
                    m = Sun((self.pos[0], self.pos[1]),
                            (self.pos[0], self.pos[1]))
                    gfw.world.add(gfw.layer.sun, m)
                elif self.name == 'Peashooter':
                    m = Bullet((self.pos[0], self.pos[1]), 'Normal')
                    gfw.world.add(gfw.layer.bullet, m)
                elif self.name == 'SnowPea':
                    m = Bullet((self.pos[0], self.pos[1]), 'snow')
                    gfw.world.add(gfw.layer.bullet, m)
                elif self.name == 'CherryBomb' and self.cherryBomb == False:
                    self.time += gfw.delta_time
                    self.fidx = round(self.time * self.fps)
                elif self.name == 'WallNut':
                    pass

        if self.name != 'CherryBomb':
            self.time += gfw.delta_time
            self.fidx = round(self.time * self.fps)
        else:  # 체리의 인덱스가 터짐이면 좀비와 충돌체크해서 주변 좀비 죽인다. 그리고 삭제된다.
            if self.fidx >= 6:
                self.cherryBomb = True
                if self.cherrybombtime == 0:
                    check_collision_cherrybomb(self.pos)
                self.cherrybombtime += gfw.delta_time
                if self.cherrybombtime > 1:
                    self.remove()
Ejemplo n.º 7
0
def generate_sun():
    x = random.randrange(100, get_canvas_width() - 100)
    y = get_canvas_height()
    targetX = x
    targetY = random.randrange(200, get_canvas_height() // 2)
    m = Sun((x, y), (targetX, targetY))
    gfw.world.add(gfw.layer.sun, m)
Ejemplo n.º 8
0
    def __init__(self, root=None):

        self.canvas = tk.Canvas(root)

        self.canvas.pack(expand=True, fill="both")

        sun = Sun(engine=self, mass=1000)
        sun_graphic = self.canvas.create_oval(sun.x - sun.radius,
                                              sun.y - sun.radius,
                                              sun.x + sun.radius,
                                              sun.y + sun.radius,
                                              fill="yellow")
        planet = Planet(engine=self, sun=sun)
        planet_graphic = self.canvas.create_oval(planet.x - planet.radius,
                                                 planet.y - planet.radius,
                                                 planet.x + planet.radius,
                                                 planet.y + planet.radius,
                                                 fill="green")
        lander = NaiveLander(engine=self,
                             sun=sun,
                             planet=planet,
                             acceleration_cap=0.5)
        lander_graphic = self.canvas.create_oval(lander.x - lander.radius,
                                                 lander.y - lander.radius,
                                                 lander.x + lander.radius,
                                                 lander.y + lander.radius,
                                                 fill="grey")
        self.graphic_dict = {
            sun: sun_graphic,
            planet: planet_graphic,
            lander: lander_graphic
        }
        self.update()
Ejemplo n.º 9
0
    def add_sun(self):

        temperature = input("I see it's hot but what is the temperature? ")
        sky = input("How is the sky looking? ")
        is_over_90 = input("Is it over 90 degrees? (True or False) ")

        new_sun = Sun(temperature, is_over_90, sky)
        self.daily_forecast.append(new_sun)
Ejemplo n.º 10
0
    def __init__(self):

        self.size = (800, 400)
        self.fps = 30
        self.screen = None

        self.sky = Sky(self)
        self.foreground = Foreground(self)
        self.sun = Sun(self)
Ejemplo n.º 11
0
def init_gl():
    global obj
    global cam
    global sun
    global mercury, venus, earth, mars, jupiter, saturn, uranus, neptune
    global planets
    global asteroid
    global t
    global quad
    global ship

    glClearColor(0.0, 0.0, 0.0, 1.0)
    glClearDepth(1.0)
    glEnable(GL_DEPTH_TEST)
    glShadeModel(GL_SMOOTH)

    glEnable(GL_LIGHTING)

    glLightfv(GL_LIGHT0, GL_AMBIENT, light_amb_0)
    glLightfv(GL_LIGHT0, GL_POSITION, light_pos_0)
    glEnable(GL_LIGHT0)

    glLightfv(GL_LIGHT1, GL_POSITION, light_pos_1)
    glLightfv(GL_LIGHT1, GL_SPOT_DIRECTION, light_dir_1)
    glLightfv(GL_LIGHT1, GL_AMBIENT, light_amb_1)
    glLightfv(GL_LIGHT1, GL_DIFFUSE, light_dif_1)
    glEnable(GL_LIGHT1)

    obj = OBJ("cube.obj", textureFile="stars.jpg")
    obj.generate()

    cam = Camera()

    sun = Sun(textureFile="sun.jpg")

    mercury = Planet("mercury.jpg", 8, 5, 0.5, 0.1, 0.25)
    venus = Planet("venus.jpg", 9.6, 6, 0.4, 0.1, 0.35)
    earth = Planet("earth.jpg", 11.2, 7, 0.3, 0.1, 0.45, "moon.jpg",
                   [0.7, 0.8, 0.09])
    mars = Planet("mars.jpg", 12.8, 8, 0.2, 0.1, 0.33)
    jupiter = Planet("jupiter.jpg", 19.2, 12, 0.2, 1, 1.5, "jupiter-moon.jpg",
                     [3, 1, 0.3])
    saturn = Planet("saturn.jpg", 25.6, 16, 0.15, 0.2, 1.1)
    uranus = Planet("uranus.jpg", 30.4, 19, 0.11, 0.2, 0.8)
    neptune = Planet("neptune.jpg", 32.8, 20.5, 0.09, 0.2, 0.7)
    planets = [mercury, venus, earth, mars, jupiter, saturn, uranus, neptune]

    quad = gluNewQuadric()
    gluQuadricTexture(quad, GL_TRUE)

    asteroid = Asteroid(Fire())

    t = Texture("rings.jpg")

    ship = pywavefront.Wavefront('Apollo/apollo.obj')
Ejemplo n.º 12
0
    def __init__(self, building_height):
        rospy.init_node('offb')
        self.height = building_height
        self.GPS_ready = False

        # Wait for Offboard and drone to be ready
        ready = rospy.wait_for_message('/gps_ready_from_offboard', Bool, timeout=rospy.Duration(60*5)) # Wait for offboard to get GPS fix for 5 minutes, because sometimes GPS locks take long to get when a board is booted up the first time

        if ready:
            nav = NavSatFix()
            # And now put the node into a waiting loop to wait for GPS Lock from Offboard
            nav = rospy.wait_for_message('mavros/global_position/global', NavSatFix)
            self.coordinates = np.array([nav.latitude, nav.longitude])
        else:
            rospy.loginfo("Never got position confirmation from Offboard")

        self.house_result_pub = rospy.Publisher('/house_results_from_overpass_local', BuildingPolygonResult, queue_size=5) # Information about the house
        self.camera_stuff_pub = rospy.Publisher('/camera_and_distances', CameraStuff, queue_size=1)
        self.impression_keyframes_pub = rospy.Publisher('/impression_poses_from_planner', PoseArray, queue_size=5) # Poses to take one image of each facade of the house
        self.inspection_keyframes_pub = rospy.Publisher('/keyframes_poses_from_planner', PoseArray, queue_size=5)

        #self.segmented_image_sub = rospy.Subscriber('segmented_image_from_cnn', cnnResult, self.segmented_image_callback, queue_size=5)

        self.image_and_rois_sub = rospy.Subscriber('/segmented_image_from_cnn', ImageAndRois, callback=self.image_and_rois_callback)

        self.get_tiles_ready = False

        self.images_list = []
        self.rois_list = []

        self.s = Sun(self.coordinates[0], self.coordinates[1])
        self.m = Mission(80, 80)
        self.model_walls = []
        self.model_windows = []

        self.fig_thread = Thread(target=self.draw_thread, args=())
        self.fig_thread.daemon = True

        self.fig = []
        self.ax = []
Ejemplo n.º 13
0
 def level2init(self):
     self.mainscreen = True
     self.planetChange = False
     self.playing = True
     self.onScreen = True
     self.shipCount = 0
     self.score = 350
     self.makePlanets()
     self.gamex, self.gamey = self.width / 2, self.height / 2
     self.initShip(self.gamex, self.gamey)
     Sun.init()
     self.sunx, self.suny, self.r = (self.width / 2, self.height / 2, 120)
     self.sun = Sun(self.sunx, self.suny)
     self.initFuel()
     self.sungroup = pygame.sprite.Group(self.sun)
     self.planetList = [self.mars, self.uranus, self.mercury, self.neptune]
     pygame.font.init()
     self.starImage = pygame.transform.rotate(
         pygame.transform.scale(
             pygame.image.load('images/stars.png').convert_alpha(),
             (self.width, self.height)), 0)
     self.counter = 0
     self.initScore = 350
Ejemplo n.º 14
0
def run_game():
    pygame.init()
    pygame.mixer.music.load('music/Phantom from Space.mp3')
    pygame.mixer.music.play(-1)
    pygame.mixer.music.set_volume(0.5)
    sw_settings = Settings()
    screen = pygame.display.set_mode(
        (sw_settings.screen_width, sw_settings.screen_height))
    pygame.display.set_caption("Earth's Defender")
    earth = Earth(sw_settings, screen)
    moon = Moon(sw_settings, screen)
    sun = Sun(sw_settings, screen)
    play_button = Button(sw_settings, screen, "Play")
    pause_message = PauseMessage(sw_settings, screen, "Pause")
    game_stats = GameStats(sw_settings)
    scoreboard = Scoreboard(sw_settings, screen, game_stats)
    ship = Ship(sw_settings, screen)
    alien_boss = AlienBoss(sw_settings, screen)
    bullets = Group()
    aliens = Group()
    aliens_bullets = Group()
    asteroids = Group()
    gf.create_fleet(sw_settings, screen, ship, aliens)

    while True:
        gf.check_events(sw_settings, screen, game_stats, scoreboard,
                        play_button, pause_message, ship, aliens, bullets,
                        aliens_bullets, asteroids)
        if game_stats.game_active and game_stats.game_pause:
            ship.update()
            gf.update_bullets(sw_settings, screen, game_stats, scoreboard,
                              ship, aliens, bullets, aliens_bullets, asteroids,
                              alien_boss)
            gf.update_aliens(sw_settings, game_stats, scoreboard, screen, ship,
                             aliens, bullets, aliens_bullets, asteroids)
            gf.check_alien_fires(sw_settings, screen, aliens, aliens_bullets)
            gf.update_aliens_bullets(sw_settings, game_stats, scoreboard,
                                     screen, ship, aliens, bullets,
                                     aliens_bullets, asteroids)
            gf.check_asteroid_fall(sw_settings, screen, asteroids)
            gf.update_asteroids(sw_settings, game_stats, scoreboard, screen,
                                ship, aliens, bullets, aliens_bullets,
                                asteroids)
            gf.update_alien_boss(sw_settings, screen, game_stats, alien_boss,
                                 aliens, aliens_bullets, bullets, asteroids)
        gf.update_screen(sw_settings, screen, earth, moon, sun, game_stats,
                         scoreboard, ship, aliens, bullets, aliens_bullets,
                         asteroids, play_button, pause_message, alien_boss)
Ejemplo n.º 15
0
def enter():
    background = Background()
    game_world.add_object(background, 0)

    ui_slot = Ui_slot()
    game_world.add_object(ui_slot, 0)

    peashooter_ui = Peashooter_ui()
    game_world.add_object(peashooter_ui, 0)

    peashooter = Peashooter()
    game_world.add_object(peashooter, 1)

    global sun
    sun = Sun()
    normal_zombie = Normal_zombie()
Ejemplo n.º 16
0
                                                    maxBytes=1 * 1024 * 1024,
                                                    backupCount=2)
file_handler.setLevel(LOG_LVL)

# Add a formatter
formatter = logging.Formatter(LOG_FORMAT)
file_handler.setFormatter(formatter)

global_logger.addHandler(file_handler)

# Add another handler that will stream to output
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setLevel(logging.ERROR)
# logger.addHandler(stream_handler)  # uncomment this to check if this works.
"""setting up lights"""
sun = Sun(LIGHTS)
"""setting up fans"""
wind = Wind(FANS)
"""
import all the configured DH22 sensors, and set them up with names
This only has the capacity for 2 sensors right now, but hopefully will allow any number in the future.
"""
for dht22_sensor in DHT22:
    if dht22_sensor[1] == 'internal':
        in_sense = Sensor(dht22_sensor[0], Adafruit_DHT.DHT22, dht22_sensor[1])
    elif dht22_sensor[1] == 'external':
        ext_sense = Sensor(dht22_sensor[0], Adafruit_DHT.DHT22,
                           dht22_sensor[1])
str_sensor = ','.join([str(x) for x in Sensor.array
                       ])  # put all the names of the sensors together
logger.info("DHT22 sensors configured: {}".format(str_sensor))
Ejemplo n.º 17
0
class Schedule(ImageContent):
    """A database-backed schedule determining which images to show at request
    time and when to wake up from sleep for the next request.

    The schedule is a list of maps, each containing:
     'name': A human-readable name for this entry.
    'start': A cron expression for the start time of this entry. (The end time
             is the start time of the next closest entry in time.) The cron
             expression syntax additionally supports the keywords 'sunrise' and
             'sunset' instead of hours and minutes, e.g. 'sunrise * * *'.
    'image': The kind of image to show when this entry is active. Valid kinds
             are 'artwork', 'city', 'commute', 'calendar', and 'everyone'.
    """
    def __init__(self, geocoder):
        self.local_time = LocalTime(geocoder)
        self.sun = Sun(geocoder)
        self.artwork = Artwork()
        self.city = City(geocoder)
        self.commute = Commute(geocoder)
        self.calendar = GoogleCalendar(geocoder)
        self.everyone = Everyone(geocoder)

    def _next(self, cron, after, user):
        """Finds the next time matching the cron expression."""

        try:
            cron = self.sun.rewrite_cron(cron, after, user)
        except DataError as e:
            raise ContentError(e)

        try:
            return croniter(cron, after).get_next(datetime)
        except ValueError as e:
            raise ContentError(e)

    def _image(self, kind, user):
        """Creates an image based on the kind."""

        if kind == 'artwork':
            content = self.artwork
        elif kind == 'city':
            content = self.city
        elif kind == 'commute':
            content = self.commute
        elif kind == 'calendar':
            content = self.calendar
        elif kind == 'everyone':
            content = self.everyone
        else:
            error('Unknown image kind: %s' % kind)
            return None

        return content.image(user)

    def image(self, user):
        """Generates the current image based on the schedule."""

        # Find the current schedule entry by parsing the cron expressions.
        try:
            time = self.local_time.now(user)
        except DataError as e:
            raise ContentError(e)
        today = time.replace(hour=0, minute=0, second=0, microsecond=0)
        while True:
            entries = [(self._next(entry['start'], today, user), entry)
                       for entry in user.get('schedule')]
            if not entries:
                raise ContentError('Empty schedule')
            past_entries = list(filter(lambda x: x[0] <= time, entries))

            # Use the most recent past entry.
            if past_entries:
                latest_datetime, latest_entry = max(past_entries,
                                                    key=lambda x: x[0])
                break

            # If there were no past entries, try the previous day.
            today -= timedelta(days=1)

        # Generate the image from the current schedule entry.
        info('Using image from schedule entry: %s (%s, %s)' %
             (latest_entry['name'], latest_entry['start'],
              latest_datetime.strftime('%A %B %d %Y %H:%M:%S %Z')))
        image = self._image(latest_entry['image'], user)

        return image

    def delay(self, user):
        """Calculates the delay in milliseconds to the next schedule entry."""

        # Find the next schedule entry by parsing the cron expressions.
        try:
            time = self.local_time.now(user)
        except DataError as e:
            raise ContentError(e)
        entries = [(self._next(entry['start'], time, user), entry)
                   for entry in user.get('schedule')]
        if not entries:
            raise ContentError('Empty schedule')
        next_datetime, next_entry = min(entries, key=lambda x: x[0])

        # Calculate the delay in milliseconds.
        seconds = (next_datetime - time).total_seconds()
        seconds += DELAY_BUFFER_S
        milliseconds = int(seconds * 1000)
        info('Using time from schedule entry: %s (%s, %s, in %d ms)' %
             (next_entry['name'], next_entry['start'],
              next_datetime.strftime('%A %B %d %Y %H:%M:%S %Z'), milliseconds))

        return milliseconds
Ejemplo n.º 18
0
def classFactory(iface):
    # load Sun class from file Sun
    from sun import Sun
    return Sun(iface)
Ejemplo n.º 19
0
 def cal_sun_loc(self):
     sun=Sun()
     sun.cal(self.days_0)
     self.planets['Sun']=sun
Ejemplo n.º 20
0
class Schedule(ImageContent):
    """User schedule processing.

    A database-backed schedule determining which images to show at request
    time and when to wake up from sleep for the next request.

    The schedule is a list of maps, each containing:
     'name': A human-readable name for this entry.
    'start': A cron expression for the start time of this entry. (The end time
             is the start time of the next closest entry in time.) The cron
             expression syntax additionally supports the keywords 'sunrise' and
             'sunset' instead of hours and minutes, e.g. 'sunrise * * *'.
    'image': The kind of image to show when this entry is active. Valid kinds
             are 'artwork', 'city', 'commute', 'calendar', and 'everyone'.
    """
    def __init__(self, geocoder):
        """Schedule constructor.

        Args:
            geocoder (geocoder.Geocoder): Used to localize user specified locations
        """
        self._local_time = LocalTime(geocoder)
        self._sun = Sun(geocoder)
        self._artwork = Artwork()
        self._city = City(geocoder)
        self._commute = Commute(geocoder)
        self._calendar = GoogleCalendar(geocoder)
        self._everyone = Everyone(geocoder)

    def _next(self, cron, after, user):
        """Find the next time matching the cron expression."""
        try:
            cron = self._sun.rewrite_cron(cron, after, user)
        except DataError as e:
            raise ContentError(e)

        try:
            return croniter(cron, after).get_next(datetime)
        except ValueError as e:
            raise ContentError(e)

    def _previous(self, cron, before, user):
        """Find the previous time matching the cron expression."""
        try:
            cron = self._sun.rewrite_cron(cron, before, user)
        except DataError as e:
            raise ContentError(e)

        try:
            return croniter(cron, before).get_prev(datetime)
        except ValueError as e:
            raise ContentError(e)

    def _image(self, kind, user, width, height):
        """Create an image based on the kind."""
        if kind == 'artwork':
            content = self._artwork
        elif kind == 'city':
            content = self._city
        elif kind == 'commute':
            content = self._commute
        elif kind == 'calendar':
            content = self._calendar
        elif kind == 'everyone':
            content = self._everyone
        else:
            error('Unknown image kind: %s' % kind)
            return None

        return content.image(user, width, height)

    def image(self, user, width, height):
        """Generate the current image based on the schedule."""
        # Find the current schedule entry by parsing the cron expressions.
        try:
            time = self._local_time.now(user)
        except DataError as e:
            raise ContentError(e)

        entries = [(self._previous(entry['start'], time, user), entry)
                   for entry in user.get('schedule')]
        if not entries:
            raise ContentError('Empty schedule')

        # Use the most recent past entry.
        latest_datetime, latest_entry = max(entries, key=lambda x: x[0])

        # Generate the image from the current schedule entry.
        info('Using image from schedule entry: %s (%s, %s)' %
             (latest_entry['name'], latest_entry['start'],
              latest_datetime.strftime('%A %B %d %Y %H:%M:%S %Z')))
        image = self._image(latest_entry['image'], user, width, height)

        return image

    def delay(self, user):
        """Calculate the delay in milliseconds to the next schedule entry."""
        # Find the next schedule entry by parsing the cron expressions.
        try:
            time = self._local_time.now(user)
        except DataError as e:
            raise ContentError(e)
        entries = [(self._next(entry['start'], time, user), entry)
                   for entry in user.get('schedule')]
        if not entries:
            raise ContentError('Empty schedule')
        next_datetime, next_entry = min(entries, key=lambda x: x[0])

        # Calculate the delay in milliseconds.
        seconds = (next_datetime - time).total_seconds()
        seconds += DELAY_BUFFER_S
        milliseconds = int(seconds * 1000)
        info('Using time from schedule entry: %s (%s, %s, in %d ms)' %
             (next_entry['name'], next_entry['start'],
              next_datetime.strftime('%A %B %d %Y %H:%M:%S %Z'), milliseconds))

        return milliseconds

    def empty_timeline(self):
        """Generate an empty timeline image."""
        image = Image.new(mode='RGB',
                          size=(TIMELINE_WIDTH, TIMELINE_HEIGHT),
                          color=TIMELINE_BACKGROUND)
        draw = Draw(image)

        # Draw each day of the week.
        num_days = len(day_abbr)
        for day_index in range(num_days):
            x = TIMELINE_DRAW_WIDTH * day_index / num_days

            # Draw a dashed vertical line.
            for y in range(0, TIMELINE_HEIGHT, 2 * TIMELINE_LINE_DASH):
                draw.line([(x, y), (x, y + TIMELINE_LINE_DASH - 1)],
                          fill=TIMELINE_FOREGROUND,
                          width=TIMELINE_LINE_WIDTH)

            # Draw the abbreviated day name.
            name = day_abbr[day_index]
            day_x = x + TIMELINE_DRAW_WIDTH / num_days / 2
            day_y = TIMELINE_HEIGHT - SCREENSTAR_SMALL_REGULAR['height']
            draw_text(name,
                      SCREENSTAR_SMALL_REGULAR,
                      TIMELINE_FOREGROUND,
                      xy=(day_x, day_y),
                      anchor=None,
                      box_color=None,
                      box_padding=0,
                      border_color=None,
                      border_width=0,
                      image=image,
                      draw=draw)

        # Draw another dashed line at the end.
        for y in range(0, TIMELINE_HEIGHT, 2 * TIMELINE_LINE_DASH):
            draw.line([(TIMELINE_DRAW_WIDTH, y),
                       (TIMELINE_DRAW_WIDTH, y + TIMELINE_LINE_DASH - 1)],
                      fill=TIMELINE_FOREGROUND,
                      width=TIMELINE_LINE_WIDTH)

        return image

    def timeline(self, user):
        """Generate a timeline image of the schedule for settings."""
        image = self.empty_timeline()
        draw = Draw(image)

        # Find the user or return the empty timeline.
        try:
            now = self._local_time.now(user)
        except DataError as e:
            return image

        # Start the timeline with the most recent beginning of the week.
        start = now.replace(hour=0, minute=0, second=0)
        start -= timedelta(days=start.weekday())
        stop = start + timedelta(weeks=1)
        start_timestamp = datetime.timestamp(start)
        stop_timestamp = datetime.timestamp(stop)
        timestamp_span = stop_timestamp - start_timestamp

        # Draw a dashed line in highlight color at the current time.
        now_timestamp = datetime.timestamp(now)
        now_x = TIMELINE_DRAW_WIDTH * (now_timestamp -
                                       start_timestamp) / timestamp_span
        for y in range(0, TIMELINE_HEIGHT, 2 * TIMELINE_LINE_DASH):
            draw.line([(now_x, y), (now_x, y + TIMELINE_LINE_DASH - 1)],
                      fill=TIMELINE_HIGHLIGHT,
                      width=TIMELINE_LINE_WIDTH)

        # Generate the schedule throughout the week.
        entries = user.get('schedule')
        if not entries:
            # Empty timeline.
            return image
        for i in range(len(entries)):
            entries[i]['index'] = i
        time = start
        while time < stop:
            # Find the next entry.
            next_entries = [(self._next(entry['start'], time,
                                        user), entry['index'], entry)
                            for entry in entries]
            next_datetime, next_index, next_entry = min(next_entries,
                                                        key=lambda x: x[0])

            # Draw the entry's index and a vertical line, with a tilde to mark
            # the variable sunrise and sunset times.
            timestamp = datetime.timestamp(next_datetime)
            x = TIMELINE_DRAW_WIDTH * (timestamp -
                                       start_timestamp) / timestamp_span
            y = TIMELINE_HEIGHT / 2
            text = str(next_index + 1)
            next_entry_start = next_entry['start']
            if 'sunrise' in next_entry_start or 'sunset' in next_entry_start:
                text = '~' + text
            box = draw_text(text,
                            SCREENSTAR_SMALL_REGULAR,
                            TIMELINE_FOREGROUND,
                            xy=(x, y),
                            anchor=None,
                            box_color=None,
                            box_padding=4,
                            border_color=None,
                            border_width=0,
                            image=image,
                            draw=draw)
            draw.line([(x, 0), (x, box[1])], fill=TIMELINE_FOREGROUND, width=1)

            # Jump to the next entry.
            time = next_datetime

        return image
Ejemplo n.º 21
0
    print("device connected to SSID {}: {}".format(SSID, wlan.isconnected()))
    print("IP adress {}".format(
        wlan.ifconfig()[0]))  # get the interface's IP/netmask/gw/DNS addresses
    print("RSSI {}".format(wlan.status('rssi')))
except:
    pass

#update RCT time form network
ntptime.host = 'pool.ntp.org'
#ntptime.settime()
now = float("{}.{}".format(localtime()[3], localtime()[4]))
print("time: {}".format(localtime()))

#calculate sunrise/sunset time
coords = {'longitude': 2.107, 'latitude': 44.584}
sun = Sun()
# Sunrise time UTC (decimal, 24 hour format)
sunrise = sun.getSunriseTime(coords)['decimal']
print("Sunrise (UTC decimal) : {}".format(sunrise))
# Sunset time UTC (decimal, 24 hour format)
sunset = sun.getSunsetTime(coords)['decimal']
print("Sunset (UTC decimal): {}".format(sunset))

#scheduling

stepPin = PWM(Pin(STEP_PIN), freq=0, duty=32)
stopTim = Timer(1)
dirPin = Pin(DIR_PIN, Pin.OUT)

#override now variable for testing
now = 7.45
Ejemplo n.º 22
0
 def run(self):
     
     while self.paused[0] == 1:
         pass
     
     sky = Sky(self.queue)
     sun = Sun(self.queue, 300, 100)
     moon = Moon(self.queue, 300, 100)
     ground = Ground(self.queue)
     
     time = 75
     self.shared[0] = time
     day = 0
     seasons = ["spring", "summer", "fall", "winter"]
     season = "spring"
     self.shared[2] = seasons.index(season)
     seasonStages = ["early", "mid", "mid", "late"]
     seasonStage = "mid"
     
     weatherOptions = ["clear", "clear", "clear", "clear", "cloudy", "cloudy", "overcast", "rain", "rain", "storm"]
     weather = choice(weatherOptions)
     self.shared[1] = weatherOptions.index(weather)
     
     self.queue.put(QueueItem("cont"))   
     self.paused[0] = 1
     self.paused[3] = 0
     while self.paused[0] == 1:
         pass
     
     while True:
         
         sky.update(time)
         sun.update(time)
         moon.update(time, day)
         ground.update(time, season, seasonStage, seasons)
         
         sun.draw()
         moon.draw()
         ground.draw()
                
         time += 3
         if time > 1600:
             time = 0
             day += 1
             if day > 15:
                 day = 0
             season = seasons[int(day/4)]
             self.shared[2] = seasons.index(season)
             seasonStage = seasonStages[day%len(seasonStages)]
             
             if season == "winter" and seasonStage == "early":
                 weather = "rain"
             else: 
                 weather = choice(weatherOptions)
         
         self.shared[0] = time
         self.shared[1] = weatherOptions.index(weather)
         self.queue.put(QueueItem("cont"))
         self.paused[0] = 1
         sleep(0.05)
         while self.paused[0] == 1:
             pass
Ejemplo n.º 23
0
 def create_sun(self):
     """Create the sun."""
     self.sun = Sun()
def main():
    global sun_num_surface, choose
    global text
    index = 0
    while True:
        clock.tick(20)
        if not pygame.mixer.music.get_busy():
            pygame.mixer.music.play()
        index += 1
        # 碰撞检测
        for bullet in bulletGroup:
            for zombie in zombieGroup:
                if pygame.sprite.collide_mask(bullet, zombie):
                    zombie.energy -= 1
                    bulletGroup.remove(bullet)
        for wallNut in wallnutGroup:
            for zombie in zombieGroup:
                if pygame.sprite.collide_mask(wallNut, zombie):
                    zombie.ismeetwallnut = True
                    wallNut.zombies.add(zombie)
        for peashooter in peashooterGroup:
            for zombie in zombieGroup:
                if pygame.sprite.collide_mask(peashooter, zombie):
                    zombie.ismeetwallnut = True
                    peashooter.zombies.add(zombie)
        for sunflower in sunFlowerGroup:
            for zombie in zombieGroup:
                if pygame.sprite.collide_mask(sunflower, zombie):
                    zombie.ismeetwallnut = True
                    sunflower.zombies.add(zombie)
        screen.blit(bg_img, (0, 0))
        screen.blit(seedbank_img, (250, 0))
        screen.blit(sun_num_surface, (270, 60))

        screen.blit(flowerSeed, (320, 0))
        screen.blit(peashooterSeed, (382, 0))
        screen.blit(wallnutSeed, (446, 0))
        sunFlowerGroup.update(index)
        sunFlowerGroup.draw(screen)
        peashooterGroup.update(index)
        peashooterGroup.draw(screen)
        bulletGroup.update(index)
        bulletGroup.draw(screen)
        zombieGroup.update(index)
        zombieGroup.draw(screen)
        wallnutGroup.update(index)
        wallnutGroup.draw(screen)
        sunGroup.update(index)
        sunGroup.draw(screen)

        (x, y) = pygame.mouse.get_pos()
        if choose == 1:
            screen.blit(sunflowerImg, (x, y))
        elif choose == 2:
            screen.blit(peashooterImg, (x, y))
        elif choose == 3:
            screen.blit(wallnutImg, (x, y))
        for event in pygame.event.get():
            if event.type == GEN_SUN_EVENT:
                for sprite in sunFlowerGroup:
                    now = time.time()
                    if now - sprite.lasttime >= 5:
                        sun = Sun(sprite.rect)
                        sunGroup.add(sun)
                        sprite.lasttime = now

            if event.type == GEN_BULLET_EVENT:
                for sprite in peashooterGroup:
                    bullet = Bullet(sprite.rect, backgdsize)
                    bulletGroup.add(bullet)

            if event.type == GEN_ZOMBIE_EVENT:
                zombie = Zombie()
                zombieGroup.add(zombie)

            if event.type == GEN_FLAGZOMBIE_EVENT:
                flagzombie = Flagzombie()
                zombieGroup.add(flagzombie)

            if event.type == pygame.QUIT:
                exit()

            if event.type == pygame.MOUSEBUTTONDOWN:
                pressed_key = pygame.mouse.get_pressed()
                if pressed_key[0] == 1:
                    x, y = pygame.mouse.get_pos()
                    print(x, y)
                    if 320 <= x <= 382 and 0 <= y <= 89 and text >= 50:
                        # 点中了太阳花
                        choose = 1
                    elif 383 <= x < 446 and 0 <= y <= 89 and text >= 100:
                        # 点中了豌豆射手
                        choose = 2
                    elif 447 <= x < 511 and 0 <= y <= 89 and text >= 50:
                        # 点中了坚果墙
                        choose = 3
                    elif 250 < x < 1200 and 90 < y < 600:
                        if choose == 1:
                            current_time = time.time()
                            sunflower = Sunflower(current_time)
                            sunflower.rect.x = x
                            sunflower.rect.y = y
                            sunFlowerGroup.add(sunflower)
                            choose = 0

                            text -= 50
                            sun_font = pygame.font.SysFont('arial', 25)
                            sun_num_surface = sun_font.render(
                                str(text), True, (0, 0, 0))
                        elif choose == 2:
                            peashooter = Peashooter()
                            peashooter.rect.y = y
                            peashooter.rect.x = x
                            peashooterGroup.add(peashooter)
                            choose = 0

                            text -= 100
                            sun_font = pygame.font.SysFont('arial', 25)
                            sun_num_surface = sun_font.render(
                                str(text), True, (0, 0, 0))
                        elif choose == 3:
                            wallnut = Wallnut()
                            wallnut.rect.y = y
                            wallnut.rect.x = x
                            wallnutGroup.add(wallnut)
                            choose = 0

                            text -= 50
                            sun_font = pygame.font.SysFont('arial', 25)
                            sun_num_surface = sun_font.render(
                                str(text), True, (0, 0, 0))
                    for sun in sunGroup:
                        if sun.rect.collidepoint(x, y):
                            sunGroup.remove(sun)
                            text += 50
                            sun_font = pygame.font.SysFont('arial', 25)
                            sun_num_surface = sun_font.render(
                                str(text), True, (0, 0, 0))

        pygame.display.update()
Ejemplo n.º 25
0
        for id, device in devices.items():
            assert isinstance(id, str)
            device['id'] = id
            d = Device(**device)
            device_list.append(d)
        device_list.post_load()
except FileNotFoundError:
    print('Error reading file "%s". Creating it.' % (settings.DEVICES_FILE,))
    devices = {
        'mk': {'type': device.Types.MOTION_SENSOR, 'room': 'kitchen', 'control': ['lk']},
        'sk': {'type': device.Types.SWITCH, 'room': 'kitchen', 'control': ['lk']},
        'lk': {'type': device.Types.LIGHT, 'room': 'kitchen'},
    }
    with open(settings.DEVICES_FILE, 'w') as file:
            print(json.dumps(devices, indent=4), file=file)

sun = Sun()
print("Dawn is at %s and dusk at %s today." % (sun.datetime('dawn').strftime('%H:%M'),
                                               sun.datetime('dusk').strftime('%H:%M')))

for i in range(0,15):
    s = my_input()
    if s == 'list':
        list_devices()
    else:
        if s:
            try:
                device_list.toggle(s)
            except KeyError:
                print('Use device names such as %s' % ','.join(device_list.list))
Ejemplo n.º 26
0
    def read(self, input):
        self.planets = []
        self.read_planets = 0  # number of planets read

        try:

            line = input.readline()
            attribute = 0  # this variable determines which attribute is being read
            self.reset_attributes()

            while line != "":
                line = "".join(line.split())  # strips all whitespaces
                if line == "":  # skip a blank row
                    line = input.readline()
                    continue
                try:
                    if attribute == 0:  # read the name
                        self.name = self.read_name(line)
                        attribute += 1
                    elif attribute == 1:  # read the mass
                        self.mass = self.read_mass(line)
                        attribute += 1
                    elif attribute == 2:  # read the diameter
                        self.diameter = self.read_diameter(line)
                        attribute += 1
                    elif attribute == 3:  # read the position vector
                        self.position = self.read_position(line)
                        attribute += 1
                    elif attribute == 4:  # read the velocity vector
                        self.velocity = self.read_velocity(line)
                        self.route = Route(self.position, self.velocity)

                        if self.name.lower() == "aurinko" or self.name.lower(
                        ) == "sun":  # check if planet is the Sun
                            planet = Sun(self.name, self.route, self.mass,
                                         self.diameter)
                            print("Succesfully saved the Sun, called {:s}".
                                  format(self.name))
                        else:
                            planet = Planet(self.name, self.route, self.mass,
                                            self.diameter)
                            print(
                                "Succesfully saved planet called {:s}".format(
                                    self.name))
                        self.planets.append(planet)
                        self.read_planets += 1
                        self.reset_attributes()
                        attribute = 0

                except Exception as e:  # if an error happened while reading an attribute
                    if self.name != None:
                        print(
                            "Failed to load a planet called {:s}. Error: {:s}".
                            format(self.name, str(e)))
                    else:
                        print(
                            "Failed to load planet number {:d} entirely! Error: {:s}"
                            .format(self.read_planets, str(e)))
                    '''
					Should implement here some code that skips to next planet
					'''

                line = input.readline()

        except:
            pass

        return self.planets
Ejemplo n.º 27
0
def getSunsetTime(longitude, latitude):
    from sun import Sun
    coords = {'longitude': longitude, 'latitude': latitude}
    sun = Sun()
    sunset = sun.getSunsetTime(coords)
    return utc2local_time(sunset['hr'], sunset['min'])
Ejemplo n.º 28
0
def main():
    global sunnum, font, fontImg
    # peashooter = Peashooter()
    clickimage = []
    # sunflower = SunFlower()
    wallnut = WallNut()
    p1 = []
    peaList = []
    sunFlowerList = []

    sunList = []
    zombieList = []
    zombie = Zombie()
    zombieList.append(zombie)

    enemy_zombie_list = []

    flower_product_list = []

    # FPS
    block = pygame.time.Clock()

    index = 0
    # 是否点击卡片
    is_pick = False
    # 区域种植判断
    is_plant = False
    # 太阳下落时间
    SUN_EVENT = pygame.USEREVENT + 1
    pygame.time.set_timer(SUN_EVENT, 3000)  # 3秒出现一个

    # 太阳花产能
    FLOWER_PRODUCT_SUM_EVENT = pygame.USEREVENT + 1
    pygame.time.set_timer(FLOWER_PRODUCT_SUM_EVENT, 5000)

    #
    ZOMBIE_EVENT = pygame.USEREVENT + 1
    pygame.time.set_timer(ZOMBIE_EVENT, 5000)

    z = Zone()
    bulletList = []
    PAUSE = False
    FINAL = 0

    while 1:

        pygame.mixer.music.play()  # 播放音乐
        block.tick(25)  # FPS为25

        # 鼠标点击
        press = pygame.mouse.get_pressed()
        # 鼠标坐标
        x, y = pygame.mouse.get_pos()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            if event.type == SUN_EVENT:
                sun = Sun()
                sunList.append(sun)
            # 太阳花产能
            if event.type == FLOWER_PRODUCT_SUM_EVENT:
                for flower in sunFlowerList:
                    if not flower.isProductSum:
                        sun = Sun()
                        sun.rect.left = flower.rect.left
                        sun.rect.top = flower.rect.top
                        sun.belong = flower
                        flower_product_list.append(sun)
                        flower.isProductSum = True  # 无法生产

            if event.type == ZOMBIE_EVENT:
                zombie = Zombie()
                zombieList.append(zombie)

            # 暂停,点击ESC
            if event.type == pygame.KEYDOWN:
                if event.key == 27:
                    PAUSE = not PAUSE

            if event.type == pygame.MOUSEMOTION:
                if 537 <= x <= 749 and 378 <= y <= 481:
                    if press[0]:
                        PAUSE = not PAUSE
                if not is_pick:
                    if press[0]:
                        if 330 <= x <= 330 + card.get_rect().width and 7 <= y <= 7 + card.get_rect().height:
                            peashooter = Peashooter()
                            clickimage.append(peashooter)
                            pick_type = 'pea'
                            is_pick = True
                        if 380 <= x <= 380 + card_1.get_rect().width and 7 <= y <= 7 + card_1.get_rect().height:
                            sunflower = SunFlower()
                            clickimage.append(sunflower)
                            pick_type = 'flower'
                            is_pick = True

                else:
                    if z.is_plant_zone(x, y):
                        if z.getIndex(x, y) and not is_plant:
                            if pick_type == 'pea':
                                p = Peashooter()
                                a, b = z.getIndex(x, y)
                                p.zone = z.getGridPos(a, b)
                                if not z.plantInfo[b][a]:
                                    p1.append(p)
                                    is_plant = True
                                    if press[0]:
                                        peaList.append(p)
                                        enemy_zombie_list.append(p)
                                        # bullet = p.shot()
                                        # bulletList.append(bullet)
                                        clickimage.clear()
                                        p1.clear()
                                        is_pick = False
                                        z.plantInfo[b][a] = 1
                                        sunnum = str(int(sunnum) - 100)
                                        fontImg = font.render(sunnum, True, (0, 0, 0))

                                        # print(z.plantInfo[a][b])
                            elif pick_type == 'flower':
                                f = SunFlower()
                                a, b = z.getIndex(x, y)
                                f.zone = z.getGridPos(a, b)
                                if not z.plantInfo[b][a]:
                                    p1.append(f)
                                    is_plant = True
                                    if press[0]:
                                        sunFlowerList.append(f)
                                        enemy_zombie_list.append(f)
                                        clickimage.clear()
                                        p1.clear()
                                        is_pick = False
                                        z.plantInfo[b][a] = 1
                                        sunnum = str(int(sunnum) - 100)
                                        fontImg = font.render(sunnum, True, (0, 0, 0))
                        else:
                            p1.clear()
                            is_plant = False

                    if press[2]:
                        is_pick = False
                        clickimage.clear()
                        p1.clear()
                        is_plant = False

                        # if 330 <= x <= 405 and 180 <= y <= 274:

                    # else:
                    #     p1.clear()

                for sun in sunList:
                    if sun.rect.collidepoint((x, y)):
                        if press[0]:
                            # 点击太阳消失
                            sunList.remove(sun)
                            # 收集加分
                            # global sunnum, font, fontImg
                            sunnum = str(int(sunnum) + 25)
                            fontImg = font.render(sunnum, True, (0, 0, 0))

                for sun in flower_product_list:
                    if sun.rect.collidepoint((x, y)):
                        if press[0]:
                            # 点击太阳消失
                            flower_product_list.remove(sun)
                            # 收集加分
                            sunnum = str(int(sunnum) + 25)
                            fontImg = font.render(sunnum, True, (0, 0, 0))
                            # 收集后可继续生产
                            sun.belong.isProductSum = False

        # 打印图片
        if int(zombie.rect.left) < 200:
            FINAL += 1
            PAUSE = True
        if not PAUSE:
            screen.blit(backgroud, (0, 0))
            screen.blit(card_slot, (250, 0))
            screen.blit(card, (330, 7))
            screen.blit(card_1, (380, 7))
            screen.blit(card_2, (430, 6))
            screen.blit(fontImg, (275, 60))

            if index > 13:
                index = 0
            # screen.blit(peashooter.images[index % 13], peashooter.rect)
            # screen.blit(sunflower.images[index % 18], sunflower.rect)
            # screen.blit(wallnut.images[index % 16], wallnut.rect)

            for image in clickimage:
                screen.blit(image.images[0], (x, y))
            for p in p1:
                screen.blit(p.images[0], p.zone)
            # 豌豆射手
            for pea in peaList:
                if pea.is_live:
                    if index % 99 == 1:
                        bullet = pea.shot()
                        bulletList.append(bullet)
                    screen.blit(pea.images[index % 13], pea.zone)
                else:
                    peaList.remove(pea)
                    enemy_zombie_list.remove(pea)
            # 太阳花
            for sunFlower in sunFlowerList:
                if sunFlower.is_live:
                    screen.blit(sunFlower.images[index % 18], sunFlower.zone)
                else:
                    sunFlowerList.remove(sunFlower)
                    enemy_zombie_list.remove(sunFlower)
            # 阳光
            for sun in sunList:
                screen.blit(sun.images[index % 22], sun.rect)
                sun.down()

            # 产能
            for sun in flower_product_list:
                screen.blit(sun.images[index % 22], sun.rect)

            for bullet in bulletList:
                if bullet.status:
                    screen.blit(bullet.images, bullet.rect)
                    bullet.move()
                    bullet.hit(zombieList)
                else:
                    bulletList.remove(bullet)

            for zombie in zombieList:
                if zombie.is_live:
                    zombie.changimage()
                    screen.blit(zombie.images[index % 20], zombie.rect)
                    zombie.move()
                    zombie.attack(enemy_zombie_list)
                else:
                    zombieList.remove(zombie)

            pygame.display.update()

            index += 1
        else:
            if FINAL > 0:
                screen.blit(final_draw, (350, 70))
            else:
                screen.blit(pause_draw, (450, 100))

        pygame.display.update()
Ejemplo n.º 29
0
 def __init__(self, geocoder):
     self._local_time = LocalTime(geocoder)
     self._sun = Sun(geocoder)
     self._weather = Weather(geocoder)
Ejemplo n.º 30
0
timezone = pytz.timezone(str(tz))

# Current brightness
is_night = False
is_night_time = False

prev_leds = []
while running:
    d = timezone.localize(datetime.now())
    utc = d.astimezone(pytz.utc)
    cur = d.timetuple()

    if loc.located():
        night_b = d.replace(hour=night[0], minute=0, second=0)
        night_e = d.replace(hour=night[1], minute=0, second=0)
        sun = Sun(lat=loc.lat, long=loc.lng)

        sunrise = sun.sunrise(utc)
        sunset = sun.sunset(utc)
        if d > sunrise:
            sunrise = sun.sunrise(utc + timedelta(days=1))
        else:
            sunset = sun.sunset(utc - timedelta(days=1))

        if d > night_e:
            night_e = night_e + timedelta(days=1)
        else:
            night_b = night_b - timedelta(days=1)

        is_night = sunset < d < sunrise
        night_length = sunrise - sunset
Ejemplo n.º 31
0
class Settings():
    def __init__(self, onChange=None):
        self.loaded = False
        self._tzcache = None
        self._ip2loccache = None
        self.hardcodedLocation = False
        self.onChange = onChange
        self.load()

    def _needsIp2LocCacheRefresh(self, datetime):
        if not self._ip2loccache:
            return True

        return self._ip2loccache['date'] < (datetime - IP2LOC_CACHE_LIFETIME)

    def _needsTzCacheRefresh(self, datetime):
        if not self._tzcache:
            return True

        if self._tzcache['coordinates'] != self.coordinates:
            return True

        return self._tzcache['date'] < (datetime - TZ_CACHE_LIFETIME)

    def _getGoogleTimezoneData(self, timestamp):
        url = TZ_URL.format(self.coordinates['latitude'], self.coordinates['longitude'], timestamp)
        response = urllib.urlopen(url, None, 2)
        result = response.read()
        if (pyVersion == 3):
            result = result.decode('utf-8')
        return json.loads(result)

    def getTimeZone(self):
        now = datetime.utcnow()

        try:
            if not(self.hardcodedLocation) and self._needsIp2LocCacheRefresh(now):
                self.loadIPCoordinates()
                self._ip2loccache = {
                    'date': now
                }

            if self._needsTzCacheRefresh(now):
                result = self._getGoogleTimezoneData(calendar.timegm(now.timetuple()))
                self._tzcache = {
                    'date': now,
                    'coordinates': self.coordinates,
                    'name': result['timeZoneName'],
                    'offset': result['dstOffset'] + result['rawOffset']
                }
                logToConsole('Using {0}'.format(result['timeZoneName']))

            return FixedOffset(self._tzcache['offset'] / 60, self._tzcache['name'])
        except Exception:
            return LocalTimezone()

    def load(self):
        settings = sublime.load_settings(PACKAGE + '.sublime-settings')
        settings.clear_on_change(PACKAGE)
        settings.add_on_change(PACKAGE, self.load)

        if not settings.has('day'):
            raise KeyError('SunCycle: missing day setting')

        if not settings.has('night'):
            raise KeyError('SunCycle: missing night setting')

        self.day = settings.get('day')
        self.night = settings.get('night')

        self.coordinates = {'latitude': settings.get('latitude', 0), 'longitude': settings.get('longitude', 0)}
        self.sun = Sun(self.coordinates)

        if self.coordinates['latitude'] != 0 or self.coordinates['longitude'] != 0:
            self.hardcodedLocation = True

        now = datetime.now(tz=self.getTimeZone())
        logToConsole('Sunrise at {0}'.format(self.sun.sunrise(now)))
        logToConsole('Sunset at {0}'.format(self.sun.sunset(now)))

        if self.loaded and self.onChange:
            self.onChange()

        self.loaded = True

    def loadIPCoordinates(self):
        try:
            response = urllib.urlopen(IP2LOC_URL, None, 2)
            result = response.read()
            if (pyVersion == 3):
                result = result.decode('utf-8')
            lookup = json.loads(result)

            self.coordinates['latitude'] = lookup['latitude']
            self.coordinates['longitude'] = lookup['longitude']
            logToConsole('Lookup lat & lng through IP: {0}'.format(self.coordinates))

            return self.coordinates
        except Exception:
            logToConsole('Failed to lookup lat & lng through IP')
coord1 = [10.32522211465866, 55.47169437449494]
coord2 = [10.32524982538288, 55.47166787993427]
coord3 = [10.32531271941916, 55.47168811627513]
coord4 = [10.32528783658924, 55.47171798510018]

utm1 = utm.from_latlon(coord1[1], coord1[0])
utm2 = utm.from_latlon(coord2[1], coord2[0])
utm3 = utm.from_latlon(coord3[1], coord3[0])
utm4 = utm.from_latlon(coord4[1], coord4[0])

lat = 55.471689
lon = 10.325267
utm_center = utm.from_latlon(lat, lon)

s = Sun(lat, lon)
m = Mission(0.8, 0.8)

local1 = [utm_center[0] - utm1[0], utm_center[1] - utm1[1]]
local2 = [utm_center[0] - utm2[0], utm_center[1] - utm2[1]]
local3 = [utm_center[0] - utm3[0], utm_center[1] - utm3[1]]
local4 = [utm_center[0] - utm4[0], utm_center[1] - utm4[1]]

height = 2.0
east_wall = Boundary(local1[0], local1[1], 0.0, local2[0], local2[1], 0.0,
                     local1[0], local1[1], height, "wall", s.get_lightsource())
south_window = Boundary(0.3857, -2.1862, 0.5, 1.3943, -1.532, 0.8, 0.3857,
                        -2.1862, 0.5 + 0.6, "window", s.get_lightsource())
north_wall = Boundary(local2[0], local2[1], 0.0, local3[0], local3[1],
                      0.0, local2[0], local2[1], height, "wall",
                      s.get_lightsource())
Ejemplo n.º 33
0
    sleep(x)
    GPIO.output(REVERSE_PIN, GPIO.LOW)
    #    GPIO.cleanup()
    debug("stopped")
    return


def debug(x):
    print(x)
    return


# This is the start of the main program

coords = {'longitude': 0.34, 'latitude': 51.1}
sun = Sun()

print sun.getSunriseTime(coords)
# Sunrise time UTC (decimal, 24 hour format)
push("hi")
print sun.getSunriseTime(coords)['hr']
print sun.getSunriseTime(coords)['min']

print sun.getSunsetTime(coords)['hr']
print sun.getSunsetTime(coords)['min']

GPIO.setmode(GPIO.BOARD)
PIR_PIN = 26
GPIO.setup(PIR_PIN, GPIO.IN)

print howfar()
Ejemplo n.º 34
0
        for a_sun in self._sun:
            print(a_sun)


if __name__ == '__main__':

    try:
        solSys1 = Solar_System()
        solSys1.add_sun('porcupine')
        print(solSys1)
    except TypeError as ve:
        print('Dealt with TypeError:', ve)

    try:
        solSys2 = Solar_System()
        sunny4 = Sun('Mayonnaise', 5, 14, 3, 23, 'yellow')
        solSys2.add_sun(sunny4)
        print(solSys2)
    except TypeError as ve:
        print('Dealt with TypeError:', ve)

    try:
        solSys3 = Solar_System()
        solSys3.add_planet('pineapple')
        print(solSys3)
    except TypeError as ve:
        print('Dealt with TypeError:', ve)

    try:
        solSys4 = Solar_System()
        planet4 = Planet('Pedro', 5, 2, 5, 'red')