コード例 #1
0
def main():

    logging.info(
        "\n\n------------------- show_images.py -------------------\n")

    dis = display.Display1593()
    dis.connect()

    dis.clear()

    fnames = [
        "images/monalisa.png", "images/einstein.jpeg", "images/audrey.jpg",
        "images/muhammedali.jpg", "images/bowie.jpg", "images/spock.jpg",
        "images/hendrix.jpg", "images/amy.png", "images/cohen.png"
    ]

    i = 0
    status = ""

    # Get current time
    start_time = datetime.now()
    hr, mn, sc = (start_time.hour, start_time.minute, start_time.second)

    brightness = bcycle[hr % 24]
    logging.info("Brightness: %d", brightness)
    logging.info("Delay time (mins): %d", args.period)

    while True:

        for f in fnames:

            logging.info("Showing image %s", f.__repr__())

            # Set brightness level
            if brightness != bcycle[hr % 24]:
                brightness = bcycle[hr % 24]
                logging.info("Brightness adjusted: %d", brightness)

            dis.show_image_calibrated(f, brightness=brightness)

            while ((datetime.now() - start_time).total_seconds() <
                   60 * args.period):
                pass

            # Get current time
            start_time = datetime.now()
            hr, mn, sc = (start_time.hour, start_time.minute,
                          start_time.second)

    exit()
コード例 #2
0
def main():

    logging.info("\n\n----------------- galaga/main.py -----------------\n")

    dis = display.Display1593()
    dis.connect()
    dis.clear()

    i = 0
    status = ""

    # Get current time
    start_time = datetime.now()
    hr, mn, sc = (start_time.hour, start_time.minute, start_time.second)

    # Use an exponentially-weighted moving average
    ewma = dis.getBrightness()
    alpha = 0.1
    history = deque([ewma])
    history_length = 32

    brightness = bcycle[hr % 24]
    logging.info("Brightness: %d", brightness)
    logging.info("Delay time (mins): %d", args.period)

    wait_time = 60 * args.period

    while True:
        for fname in fnames:

            logging.info("Showing image %s", fname.__repr__())

            # Set brightness level
            if brightness != bcycle[hr % 24]:
                brightness = bcycle[hr % 24]
                logging.info("Brightness: %d", brightness)

            filepath = os.path.join(image_dir, fname)
            dis.show_image_calibrated(filepath, brightness=brightness)

            while ((datetime.now() - start_time).total_seconds() < wait_time):
                time.sleep(1)

            # Get current time
            start_time = datetime.now()
            hr, mn, sc = (start_time.hour, start_time.minute,
                          start_time.second)

    exit()
コード例 #3
0
ファイル: clock.py プロジェクト: billtubbs/display1593
def main(argv):
    """Demonstration of how to use this module."""

    logging.info("\n\n------------- Analog Clock Display -------------\n")
    logging.info("Displays current time as an analog clock face.")

    dis = display.Display1593()
    dis.connect()
    dis.clear()

    # Get current time
    t = datetime.now().time()
    hr, min = (t.hour, t.minute)

    logging.info("Displaying clock...")

    try:
        color = argv[0]
    except IndexError:
        color = 'r'

    try:
        imax = int(argv[1])
    except IndexError:
        imax = 200

    img_old = Image.fromarray(np.zeros((256, 256, 4), dtype='uint8'), 'RGBA')
    img_new = clock_image(t)
    show_image_inc(dis, img_old, img_new)
    img_old = img_new

    hr, min, s = t.hour, t.minute, t.second

    while True:
        logging.info("%02d:%02d" % (hr, min))

        while t.minute == min:
            while datetime.now().time().second == s:
                pass
            t = datetime.now().time()

        img_new = clock_image(t)
        show_image_inc(dis, img_old, img_new)
        img_old = img_new

        min = t.minute
        if min == 0:
            hr = t.hour
コード例 #4
0
def main():

    logging.info("\n\n------------------- show_image.py -------------------\n")

    dis = display.Display1593()
    dis.connect()
    dis.clear()

    # Parameter for calculating exponentially-weighted
    # moving average (EWMA)
    alpha = 0.1

    # Initialize with average of series of readings from sensor
    brightness_ewma = np.array(
        [dis.getBrightness() for i in range(5)]
    ).mean()
    brightness_level = 0  # Image will be displayed first time

    while True:

        # Get current time
        start_time = datetime.now()
        sec = start_time.second

        # Read light level from photo resistor
        brightness = dis.getBrightness()

        # Update EWMA
        brightness_ewma = alpha * brightness + (1 - alpha) * brightness_ewma

        # See if image needs adjusting
        new_level = calculate_brightness_level(brightness_ewma)
        if new_level != brightness_level:
            brightness_level = new_level
            logging.info("Brightness: %d", brightness_level)
            logging.info("Showing image %s", args.filename.__repr__())
            f = os.path.join(images_dir, args.filename)
            dis.show_image_calibrated(f, brightness=brightness_level)

        #logging.info("Brightness: {:.2f}, {}".format(
        #             brightness_ewma, new_level))
        while (datetime.now().second == sec):
            time.sleep(0.05)  # Short wait
コード例 #5
0
ファイル: digclock.py プロジェクト: billtubbs/display1593
    def __init__(self, color='r', imax=64):
        """Create an instance of DigitalClock.

        Arguments:
        color  - string containing only 'r', 'g' and 'b'.
        imax   - maximum intensity value (brightness) of LEDs."
        """

        if not all([c in 'rgb' for c in color]):
            raise ValueError("color must be a string containing only 'r', 'g' "
                             "and 'b'.")
        self.rgb = [c in color for c in 'rgb']
        self.imax = imax

        # Connect to LED display
        self.dis = display.Display1593()
        self.dis.connect()
        self.dis.clear()

        # Initialise display memory
        self.smem = [0] * 1593
        self.smem_prev = [0] * 1593
コード例 #6
0
ファイル: shapes.py プロジェクト: billtubbs/display1593
        speed = random.uniform(0.05, 0.25)
        direction = random.uniform(0, math.pi * 2)

        if stype == "triangle":
            rotation = random.uniform(-math.pi / 720, math.pi / 720)
        else:
            rotation = 0

        return (stype, [x, y], sizes, colour, speed, direction, rotation)


logging.info("\n\n-------------- shapes.py --------------\n")
logging.info("Display slowly moving random shapes.")
logging.info("Screen brightness: %f", brightness)

dis = display.Display1593()
dis.connect()
dis.clear()

# Use this to initialize a pygame window
#screen = pygame.display.set_mode((width, height))
#pygame.display.set_caption('Shapes')

# Use this if you do not want to have a visible window
logging.info("Starting pygame...")
screen = pygame.Surface((width, height))
clock = pygame.time.Clock()

number_of_shapes = 10
my_shapes = []
logging.info("Initializing %d shapes...", number_of_shapes)
コード例 #7
0
ファイル: schelling.py プロジェクト: billtubbs/display1593
def main():

    logging.info(
        "\n\n------- Schelling Segregation Model Simulation -------\n")

    # Get current time
    start_time = datetime.now()
    hr, mn, sc = (start_time.hour, start_time.minute, start_time.second)

    # Connect to LED display
    dis = display.Display1593()
    dis.connect()

    cols = [
        display.leds.colour['orange'], display.leds.colour['green'],
        display.leds.colour['grey'], display.leds.colour['blue'],
        display.leds.colour['brown'], display.leds.colour['yellow'],
        display.leds.colour['dark red']
    ]

    while True:

        logging.info("Initializing population model...")

        # Randomly assign population and model parameters
        # Number of population groups
        p = [0.5, 0.4, 0.1]
        n_groups = np.random.choice(range(2, 5), p=p)

        # Number of neighbours in happiness calculation
        n_neighbours = 9

        # Happiness thresholds
        thresholds = np.random.choice([0.25, 0.35, 0.5], size=n_groups)

        # Number of agents
        n_agents = display.leds.numCells - (100 + n_groups * 100)

        x = [(np.random.rand() + 0.25) for i in range(n_groups)]
        t = sum(x)
        probs = [p / t for p in x]

        # Randomly sort the colours
        shuffle(cols)

        population = Population(dis,
                                n_agents,
                                probs,
                                thresholds,
                                n_neighbours=n_neighbours,
                                cols=cols[0:n_groups])

        logging.info("%d agents initialized.", n_agents)
        logging.info("%d population groups.", population.n_groups)
        logging.info("Distribution: %s", str(population.probs))
        logging.info("Thresholds: %s", str(thresholds.tolist()))
        logging.info("Number of nearest neighbours: %d", n_neighbours)

        logging.info("Displaying initial population...")
        dis.clear()
        population.show()

        logging.info("Model updating started...")
        while population.update_agents():
            pass

        logging.info("Stable population reached.")
        d = 2
        logging.info("Waiting %d mins...", d)
        time.sleep(d * 60)

    logging.info("Results")
    logging.info("   #:   id,  g,       x,       y, nn, neighbour_ids")
    for i, agent in enumerate(population.agents):
        logging.info("%4d: %4d, %2d, %7.2f, %7.2f, %2d, %s", i, agent.id,
                     agent.group, agent.location[0], agent.location[1],
                     agent.like_neighbours, str(agent.neighbour_ids))
コード例 #8
0
ファイル: solar_flares.py プロジェクト: billtubbs/display1593
def main():

    logging.info("\n\n----------------- solar_flares.py -----------------\n")

    logging.info("Image refresh rate (mins): %d", args.delay)
    crop_size = (128, 128)
    logging.info("Snapshot image size: %s", crop_size)

    dis = display.Display1593()
    dis.connect()
    dis.clear()

    status = "load"
    load_time = None

    # Parameter for calculating exponentially-weighted
    # moving average (EWMA)
    alpha = 0.1

    # Initialize with average of series of readings from sensor
    brightness_ewma = np.array([dis.getBrightness() for i in range(5)]).mean()
    brightness_level = 0  # Image will be displayed first time

    while True:

        if status == 'load':
            # Timer to count down to next image refresh
            load_time = time.time()
            logging.info("Downloading new image...")
            headers = {
                'User-Agent': 'solar_flares.py',
                'From': '*****@*****.**'
            }
            img = download_image(url, headers=headers)
            logging.info("New image downloaded")
            logging.info("Image size: %s", img.size)
            img_mb = sys.getsizeof(img.tobytes()) // 1000000
            logging.info("Image size (MB): %.2f", img_mb)
            filepath = os.path.join(images_dir, filename1)
            img.save(filepath)
            #img = Image.open(filepath)

            # Trim image to remove text
            margin = 48
            img_cropped = img.crop(
                (margin, margin, img.size[0] - margin, img.size[1] - margin))
            logging.info("Finding brightest spot...")
            left, top, right, bottom = find_brightest_area(img_cropped,
                                                           crop_size=crop_size)
            logging.info("Co-ordinates: (%d, %d, %d, %d)", left, top, right,
                         bottom)
            img_snapshot = img_cropped.crop((left, top, right, bottom))
            logging.info("Snapshot size: %s", img_snapshot.size)
            filepath = os.path.join(images_dir, filename2)
            img_snapshot.save(filepath)
            logging.info("Snapshot image saved to '%s'", filepath)
            status = 'display'
        elif status == 'wait':
            if (time.time() - load_time) // 60 >= args.delay:
                status = 'load'

        # Get current time
        sec = datetime.now().second

        # Read light level from photo resistor
        brightness = dis.getBrightness()

        # Update EWMA
        brightness_ewma = alpha * brightness + (1 - alpha) * brightness_ewma

        # See if image needs updating
        new_level = calculate_brightness_level(brightness_ewma)
        if new_level != brightness_level or status == 'display':
            if new_level != brightness_level:
                brightness_level = new_level
                logging.info("Brightness: %d", brightness_level)
            filepath = os.path.join(images_dir, filename2)
            dis.show_image_calibrated(filepath, brightness=brightness_level)
            logging.info("Image displayed: '%s'", filename2)
            if status == 'display':
                status = 'wait'

        while (datetime.now().second == sec):
            time.sleep(0.10)  # Short wait