コード例 #1
0
def play_video():
    global player

    if currentlyPlaying is "SD":
        led.color = Color('gold')

        if player is not None:
            player.kill()
            sleep(0.5)

        command = ['/usr/bin/tvservice -c "PAL 4:3"']
        subprocess.call(command, shell=True)
        sleep(0.5)
        uri = '/medilogik/SD-Sample.mp4'
        player = subprocess.Popen(
            ['omxplayer', '--no-osd', '--no-keys', '--blank', '--loop', uri],
            stdout=subprocess.DEVNULL)

    else:
        led.color = Color('green')

        if player is not None:  # i.e. first run
            player.kill()
            sleep(0.5)
            command = [
                '/usr/bin/tvservice -p'
            ]  # not needed on first run as output defaults to HDMI as HDMI connector is always present in demo box
            subprocess.call(command, shell=True)
            sleep(0.5)

        uri = '/medilogik/HD-Sample.mp4'
        player = subprocess.Popen(
            ['omxplayer', '--no-osd', '--no-keys', '--blank', '--loop', uri],
            stdout=subprocess.DEVNULL)
コード例 #2
0
    def scroll_text(self,
                    text,
                    font='default.pil',
                    size=8,
                    foreground=Color('white'),
                    background=Color('black'),
                    direction='left',
                    duration=None,
                    fps=None):
        """
        Renders *text* in the specified *font* and *size*, and scrolls the
        result across the display.

        See the :func:`scroll_text` function for more information on the
        meaning of the parameters. This method simply calls that function with
        the provided parameters, and passes the result to :meth:`play`.
        """
        # pylint: disable=too-many-arguments
        frames = scroll_text(text, font, size, foreground, background,
                             direction, duration,
                             self.fps if fps is None else fps)
        # Pre-calc all the frames in the raw RGR565 format; doesn't take a huge
        # amount of memory and ensures a smooth playback even on tiny
        # platforms like the A+
        frames = [image_to_rgb565(frame) for frame in frames]
        self.play(frames)
コード例 #3
0
ファイル: exercise.py プロジェクト: bjlovejoy/workoutPi
    def handle_regular(self, num, button, led, buzzer, oled):
        num *= self.multiplier
        log_data("Print to OLED: " + str(num) + " " + self.unit)
        oled.num_with_exercise(num, self.unit, self.name.replace("_", " "))
        sleep(0.5)

        if self.style == "num":
            button.wait_for_press()    #When finished with exercise
            sleep(0.1)
        
        elif self.style == "time":
            button.wait_for_press()    #To start timer
            led.off()
            sleep(3)
            led.color = Color("green")
            sleep(num)
            led.off()
            buzzer.on()
            sleep(0.5)
            buzzer.off()
        
        else:
            log_data("ERROR: style not supported -> " + self.style + " -> " + self.name)
            for i in range(10):
                led.color = Color("red")
                sleep(0.1)
                led.off()
                sleep(0.1)
            sys.exit()
コード例 #4
0
def main():
    signal(SIGTERM, sigterm)
    width = height = 8
    colors = {
        'unvisited': Color('black'),
        'visited': Color('black'),  #kan yellow
        'wall': Color('red'),
        'ball': Color('white'),
        'goal': Color('yellow'),  #was green
    }
    with ps.SenseHAT() as hat:
        while True:
            maze = generate_maze(width, height, colors)
            inputs = moves(hat.imu)
            outputs = game(maze, colors, inputs)
            display(hat.screen, outputs)

            maze1 = generate_maze1(width, height, colors)
            outputs1 = game1(maze1, colors, inputs)
            display(hat.screen, outputs1)

            maze2 = generate_maze2(width, height, colors)
            outputs2 = game2(maze2, colors, inputs)
            display(hat.screen, outputs2)

            maze3 = generate_maze3(width, height, colors)
            outputs3 = game3(maze3, colors, inputs)
            display(hat.screen, outputs3)
コード例 #5
0
def test_color_from_yuv():
    verify_color(Color.from_yuv(0, 0, 0), (0.0, 0.0, 0.0))
    verify_color(Color.from_yuv(1, 0, 0), (1.0, 1.0, 1.0))
    verify_color(Color.from_yuv(-1, 0, 0), (0.0, 0.0, 0.0))
    verify_color(Color.from_yuv(2, 0, 0), (1.0, 1.0, 1.0))
    verify_color(Color.from_yuv(y=0.299, u=-0.14713769751693, v=0.615),
                 (1.0, 0.0, 0.0))
コード例 #6
0
def play_video():
    global player

    if switch_SD_HD.is_pressed:  # Switch is in the 'SD' position
        led.color = Color('gold')

        if player is not None:
            player.stop()
            sleep(0.5)

        command = ['/usr/bin/tvservice -c "PAL 4:3"']
        subprocess.call(command, shell=True)
        sleep(0.5)
        VIDEO_PATH = Path("/video/SD_DemoVideo.mp4")
        player = OMXPlayer(VIDEO_PATH,
                           args=['--no-osd', '--no-keys', '--blank', '--loop'])

    else:
        led.color = Color('green')

        if player is not None:  # i.e. first run
            player.stop()
            sleep(0.5)
            command = [
                '/usr/bin/tvservice -p'
            ]  # not needed on first run as output defaults to HDMI as HDMI connector is always present in demo box
            subprocess.call(command, shell=True)
            sleep(0.5)

        VIDEO_PATH = Path("/video/HD_DemoVideo.mp4")
        player = OMXPlayer(VIDEO_PATH,
                           args=['--no-osd', '--no-keys', '--blank', '--loop'])
コード例 #7
0
def test_screen_play(screen_array):
    with mock.patch('time.sleep') as sleep:
        played = []

        def sleep_patch(delay):
            played.append((delay, screen_array.copy()))

        sleep.side_effect = sleep_patch
        with SenseScreen(fps=1) as screen:
            animation = [
                np.array([Color(c).rgb565] * 64, np.uint16).reshape((8, 8))
                for c in ('red', 'green', 'blue')
            ]
            screen.play(animation)
            assert len(animation) == len(played)
            for aframe, (pdelay, pframe) in zip(animation, played):
                assert pdelay == 1
                assert (aframe == pframe).all()
            del played[:]  # XXX 2.7 compat for .clear()
            animation = [
                np.array([Color(c).rgb565] * 64, np.uint16).reshape((8, 8))
                for c in ('yellow', 'magenta', 'cyan')
            ]
            screen.fps = 20
            screen.play([rgb565_to_image(frame) for frame in animation])
            assert len(animation) == len(played)
            for aframe, (pdelay, pframe) in zip(animation, played):
                assert pdelay == 1 / 20
                assert (aframe == pframe).all()
コード例 #8
0
ファイル: renderers.py プロジェクト: pombredanne/piwheels
 def _render_stats(self, buf, pulse):
     for (x, y), stat in self.controls.items():
         buf[y, x] = stat.color
     x, y = self.position
     base = Color(*buf[y, x])
     grad = list(base.gradient(Color('white'), steps=15))
     buf[y, x] = grad[pulse]
コード例 #9
0
def test_screen_image(screen_array):
    expected = [Color('yellow')] * 32 + [Color('magenta')] * 32
    expected = np.array([c.rgb565 for c in expected], np.uint16).reshape(
        (8, 8))
    screen_array[:] = expected
    with SenseScreen() as screen:
        assert (image_to_rgb565(screen.image()) == expected).all()
コード例 #10
0
ファイル: anim.py プロジェクト: cajturner/pisense-1
def scroll_text(text, font='default.pil', size=8, foreground=Color('white'),
                background=Color('black'), direction='left',
                duration=None, fps=15):
    """
    Generator function which yields a series of frames depicting *text*
    scrolling in *direction* across the display. Each frame will be a
    :class:`~PIL.Image.Image` 8x8 pixels in size.

    The *text*, *font*, *size*, *foreground*, and *background* parameters are
    all equivalent to those in :func:`draw_text` (which is called to handle
    rendering the text).

    The *direction* parameter defaults to 'left' which results in the text
    scrolling from the right-hand side of the display towards the left (the
    typical direction for left-to-right languages). The value 'right' can also
    be specified to reverse the scrolling direction.

    The *duration* and *fps* parameters control how many frames will be yielded
    by the function. The *duration* parameter measures the length of the
    animation in seconds, while *fps* controls how many frames should be shown
    per second. Hence, if *duration* is 2 and *fps* is 15, the
    generator will yield 30 frames.

    The default for *duration* is ``None`` indicating that the function should
    determine the duration based on the length of the rendered text (in this
    case *fps* is ignored). In this case the generator will produce frames
    which scroll 1 pixel horizontally per frame.

    The resulting animation will start with a full frame of *background* color;
    the text will appear to scroll onto the display, and off again with the
    final frame guaranteed to be another full frame of *background* color.
    """
    # pylint: disable=too-many-arguments
    #
    # +8 for blank screens either side (to let the text scroll onto and
    # off of the display) and +1 to compensate for spillage due to anti-
    # aliasing
    img = draw_text(text, font, size, foreground, background,
                    padding=(9, 0, 9, 0))
    if duration is None:
        steps = img.size[0] - 8
    else:
        steps = int(duration * fps)
    x_inc = (img.size[0] - 8) / steps
    try:
        x_steps = {
            'left': range(steps),
            'right': range(steps, -1, -1),
        }[direction]
    except KeyError:
        raise ValueError('invalid direction')
    for frame in (
            img.crop((x, 0, x + 8, img.size[1]))
            for x_step in x_steps[:-1] # exclude last frame (see below)
            for x in (int(x_step * x_inc),)
        ):
        yield frame
    # Guarantee the final frame is solid background color
    yield Image.new('RGB', (8, 8), background.rgb_bytes)
コード例 #11
0
ファイル: renderers.py プロジェクト: pdtopdog/piwheels
 def _render_queue(self, buf, pulse):
     # Then the queue length bar
     pkgs = 8 * max(0, self.status.get('builds_pending', 0)) / 64
     buf[2, :] = [
         Color('white') if x < int(pkgs) else self.blue_grad[int(
             32 * (pkgs - int(pkgs)))] if x < pkgs else Color('blue')
         for x in range(8)
     ]
コード例 #12
0
def test_rgbled_bad_color_name_nopwm():
    with RGBLED(1, 2, 3, pwm=False) as led:
        with pytest.raises(ValueError):
            led.color = Color('green')  # html 'green' is (0, ~0.5, 0)
        with pytest.raises(ValueError):
            led.color = Color(0.5, 0, 0)
        with pytest.raises(ValueError):
            led.color = Color(250, 0, 0)
コード例 #13
0
ファイル: XmasTree_Swirl.py プロジェクト: wasauce/XmasTree
def Spiral():
    length = len(SPIRAL)
    for number, val in enumerate(SPIRAL): # up from bottom
      print("S",number,number/length,val)
      tree[val].color = Color.from_hsv(0.8,number/length,1).rgb
    for number, val in reversed(list(enumerate(SPIRAL))): # down from top
      print("S",number,number/length,val)
      tree[val].color = Color.from_hsv(0.8,number/length,1).rgb
コード例 #14
0
ファイル: renderers.py プロジェクト: pdtopdog/piwheels
 def __init__(self):
     super().__init__()
     self.slaves = SlaveList()
     self.status = {}
     self.position = (0, 3)
     self.limits = (0, 3, 7, 7)
     self.last_message = datetime(1970, 1, 1)
     self.blue_grad = list(Color('blue').gradient(Color('white'), 32))
コード例 #15
0
ファイル: renderers.py プロジェクト: pdtopdog/piwheels
 def _render_slaves(self, buf, pulse):
     # Then the slave status pixels
     for index, slave in enumerate(self.slaves):
         x, y = self._slave_coords(index)
         buf[y, x] = slave.color
     x, y = self.position
     base = Color(*buf[y, x])
     grad = list(base.gradient(Color('white'), steps=15))
     buf[y, x] = grad[pulse]
コード例 #16
0
def rgb():
	colors = [Color('red'), Color('green'), Color('blue')] # add more if you like

	timeout = time.time() + ShowFor
	while True:
		for color in colors:
			tree.color = color
		if time.time() > timeout:
			break;
コード例 #17
0
ファイル: renderers.py プロジェクト: pdtopdog/piwheels
 def _render_disk(self, buf, pulse):
     # Then the disk-free bar
     disk = (8 * self.status.get('disk_free', 0) /
             self.status.get('disk_size', 1))
     buf[1, :] = [
         Color('white') if x < int(disk) else self.blue_grad[int(
             32 * (disk - int(disk)))] if x < disk else Color('blue')
         for x in range(8)
     ]
コード例 #18
0
ファイル: renderers.py プロジェクト: pombredanne/piwheels
 def _render_slaves(self, buf, pulse):
     for index, slave in enumerate(self.slaves):
         x, y = self._slave_coords(index)
         if 0 <= x < 8 and 0 <= y < 8:
             buf[y, x] = slave.color
     x, y = self.position
     base = Color(*buf[y, x])
     grad = list(base.gradient(Color('white'), steps=15))
     buf[y, x] = grad[pulse]
コード例 #19
0
def test_screen_draw(screen_array):
    expected = [Color('yellow')] * 32 + [Color('magenta')] * 32
    expected = np.array([c.rgb565 for c in expected], np.uint16).reshape(
        (8, 8))
    with SenseScreen() as screen:
        screen.draw(rgb565_to_image(expected))
        assert (screen_array == expected).all()
        with pytest.raises(ValueError):
            screen.draw(rgb565_to_image(expected).crop((0, 0, 4, 4)))
コード例 #20
0
def onebyone():
	colors = [Color('red'), Color('green'), Color('blue')] # add more if you like

	timeout = time.time() + ShowFor
	while True:
		for color in colors:
			for pixel in tree:
				pixel.color = color
		if time.time() > timeout:
			break;
コード例 #21
0
 def clear(self, fill=Color('black')):
     """
     Set all pixels in the display to the same *fill* color, which defaults
     to black (off). *fill* can be a :class:`~colorzero.Color` instance, or
     anything that could be used to construct a :class:`~colorzero.Color`
     instance.
     """
     if not isinstance(fill, Color):
         fill = Color(*fill)
     self.raw = fill.rgb565
コード例 #22
0
ファイル: states.py プロジェクト: pdtopdog/piwheels
 def color(self):
     """
     Calculate a simple color indicator for the slave.
     """
     if self.last_seen is not None:
         if datetime.utcnow() - self.last_seen > timedelta(minutes=15):
             return Color('#760')  # silent
         elif datetime.utcnow() - self.last_seen > self.timeout:
             return Color('red')  # dead
     return self._color
コード例 #23
0
def random_color():
    colors = [
        Color('red'),
        Color('green'),
        Color('blue'),
        Color('yellow'),
        Color('purple')
    ]
    color = random.choice(colors)
    return color
コード例 #24
0
ファイル: renderers.py プロジェクト: pombredanne/piwheels
 def __iter__(self):
     buf = array(Color('black'))
     grad = list(Color('darkblue').gradient(Color('white'), steps=15))
     pulse = iter(bounce(range(len(grad))))
     while True:
         offset = next(self.offset)
         buf[:, :] = self.text[:, offset:offset + 8]
         buf[:3, :] = Color('darkblue')
         x, y = self.position
         buf[:3, x] = grad[next(pulse)]
         yield buf
コード例 #25
0
def classical(duration):
    t = 0
    while (t < duration / 2):
        colors = []
        for i in range(len(tree)):
            colors.append(
                choice([Color('red'),
                        Color('green'),
                        Color('yellow')]))
        tree.value = colors
        t = t + 1
        sleep(2)
コード例 #26
0
def test_rgbled_color_name_pwm():
    with RGBLED(1, 2, 3) as led:
        assert led.value == (0, 0, 0)
        led.color = Color('white')
        assert led.value == (1, 1, 1)
        led.color = Color('green')
        assert led.value == (0, 0.5019607843137255, 0)
        led.color = Color('chocolate')
        assert led.value == (0.8235294117647058, 0.4117647058823529,
                             0.11764705882352941)
        led.color = Color('purple')
        assert led.value == (0.5019607843137255, 0.0, 0.5019607843137255)
コード例 #27
0
ファイル: renderers.py プロジェクト: pdtopdog/piwheels
 def __init__(self, main):
     super().__init__()
     self.main = main
     self.limits = (0, 0, 5, 0)
     self.back = None
     self.text = None
     self.ping_grad = list(Color('green').gradient(Color('red'), steps=64))
     self.disk_grad = list(
         Color('red').gradient(Color('green'), steps=64, easing=ease_out))
     self.offset = cycle([8])
     self.update_back()
     self.update_text()
コード例 #28
0
ファイル: exercise.py プロジェクト: bjlovejoy/workoutPi
    def wait_for_input(self, intensity, button, led, buzzer):
        """
        intensity: yoga, challenge, vigorous, moderate, easy (str)
        led, button, buzzer: pass gpiozero objects from main script
        """
        
        num = 0
        self.button_pressed = False
        colors = [Color("red"), Color("orangered"), Color("yellow"), Color("green"), Color("blue"), Color("purple"), Color("white")]

        if intensity == "challenge":
            num = 7

        else:
            num = 3
            if intensity == "yoga":
                color = colors[5]
            elif intensity == "vigorous":
                color = colors[0]
            elif intensity == "moderate":
                color = colors[1]
            elif intensity == "easy":
                color = colors[2]

        for i in range(num):
            if intensity == "challenge":
                color = colors[i]
            buzzer.on()
            led.color = color
            sleep(0.1)
            buzzer.off()
            led.off()
            sleep(0.1)

        start = time()
        delay_sec = 60  #how long to wait before sounding the buzzer reminder

        while not self.button_pressed:

            if time() - start > delay_sec:
                self.notify_and_wait(0.2, button, buzzer, True)
                self.notify_and_wait(0.2, button, buzzer, False)
                start = time()
            else:
                self.notify_and_wait(0.2, button, led, True, color)
                if self.button_pressed:
                    self.notify_and_wait(0.01, button, led, False)
                else:
                    self.notify_and_wait(0.8, button, led, False)
        
        sleep(0.3)
        led.color = color
コード例 #29
0
ファイル: keyLock.py プロジェクト: tonnsama/myHomeApp
def wrongCard(key_state):
  for i in range(3):
    led.color = Color('red')
    sleep(0.1)
    led.off()
    sleep(0.1)

  if key_state:
    print('Current state is Locked')
    led.color = Color('red')
  else:
    print('Current state is Unlocked')
    led.color = Color('blue')
コード例 #30
0
def red_to_blue(duration):
    hue = 1.0
    t = 0
    tree.color = Color.from_hsv(hue, 1.0, 0.5)
    while t < duration * 20:
        relt = t % 100
        if relt > 50:
            hue = 1.0 - ((100 - relt) / 50.0 * 0.4)
        else:
            hue = 1.0 - (relt / 50.0 * 0.4)
        tree.color = Color.from_hsv(hue, 1.0, 0.5)
        t = t + 1
        sleep(0.05)