def turn_lights_off(strip: ws.PixelStrip, runtime: float = RUNTIME):
    print(f"Turning the lights off over {runtime}s")
    weather = get_weather()
    WEATHER_ANIMATIONS[weather](strip, runtime, reverse=True)
    for i in range(strip.numPixels()):
        strip.setPixelColor(i, ws.Color(0, 0, 0))
    strip.show()
Esempio n. 2
0
class WS2812(Driver):
    """
    Legacy driver. Passes through calls to some other driver.
    """
    def __init__(self, width, height, serpentine=False, name=None):
        self.serpentine = serpentine
        super().__init__(np.zeros((height, width, 3), dtype=np.uint8),
                         8,
                         name=name)
        self.pixelstrip = PixelStrip(self.height * self.width, LED_PIN,
                                     LED_FREQ_HZ, LED_DMA, LED_INVERT,
                                     LED_BRIGHTNESS, LED_CHANNEL, LED_GAMMA)

    def __enter__(self):
        self.pixelstrip.begin()
        return super().__enter__()

    def show(self):
        if self.serpentine:
            # TODO: handle serpentine, but i don't have hardware to test :(
            outbuf = self.rawbuf
        else:
            outbuf = self.rawbuf
        outbuf = outbuf.reshape(self.width * self.height, 3)
        for i in range(outbuf.shape[0]):
            self.pixelstrip.setPixelColorRGB(i, *outbuf[i].tolist())  # ugh
        self.pixelstrip.show()
        super().show()
Esempio n. 3
0
class LED:

    def __init__(self):

        # LED Strip configuration:
        # Number of LED pixels
        LED_COUNT = 4
        # GPIO pin connected to the pixels (10 uses SPI /dev/spidev0.0)
        LED_PIN = 10
        # LED signal frequency in hertz (usually 800khz)
        LED_FREQ_HZ = 800000
        # DMA channel to use for generating signal (try 10)
        LED_DMA = 10
        # Set to 0 for darkest and 255 for brightest
        LED_BRIGHTNESS = 100
        # True to invert the signal (when using NPN transistor level shift)
        LED_INVERT = False
        # set to '1' for GPIOs 13. 19, 41, 45 or 53
        LED_CHANNEL = 0
        # Create NeoPixel object with appropriate configuration.
        self.strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)
        # Intialize the library (must be called once before other functions).
        self.strip.begin()

    def set_color(self, led, red, green, blue):
        self.strip.setPixelColor(led, Color(red, green, blue))
        self.strip.show()
Esempio n. 4
0
class PlasmaWS281X(Plasma):
    def __init__(self,
                 light_count,
                 gpio_pin=13,
                 strip_type='WS2812',
                 channel=1,
                 brightness=255,
                 freq_hz=800000,
                 dma=10,
                 invert=False):
        from rpi_ws281x import PixelStrip, ws

        strip_types = {}
        for t in ws.__dict__:
            if '_STRIP' in t:
                k = t.replace('_STRIP', '')
                v = getattr(ws, t)
                strip_types[k] = v

        strip_type = strip_types[strip_type]
        self._strip = PixelStrip(light_count, gpio_pin, freq_hz, dma, invert,
                                 brightness, channel, strip_type)
        self._strip.begin()

        Plasma.__init__(self, light_count)

    def show(self):
        """Output the buffer."""
        for i in range(self._strip.numPixels()):
            r, g, b, brightness = self._pixels[i]
            self._strip.setPixelColorRGB(i, r, g, b)

        self._strip.show()
Esempio n. 5
0
class WS2812(Driver):
    """
    Legacy driver. Passes through calls to some other driver.
    """

    def __init__(self, width, height, led_pin=18, map=None, name=None):
        self.map = map
        if self.map is None:
            n_leds = self.height * self.width
        else:
            n_leds = len(self.map)
        super().__init__(np.zeros((height, width, 3), dtype=np.uint8), 8, name=name)
        self.pixelstrip = PixelStrip(n_leds, led_pin, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL, LED_GAMMA)

    def __enter__(self):
        self.pixelstrip.begin()
        return super().__enter__()

    def show(self):
        if self.map is not None:
            outbuf = self.rawbuf[self.map]
        else:
            outbuf = self.rawbuf
        outbuf = outbuf.reshape(-1, 3)
        for i in range(outbuf.shape[0]):
            self.pixelstrip.setPixelColorRGB(i, *outbuf[i].tolist()) # ugh
        self.pixelstrip.show()
        super().show()
Esempio n. 6
0
class PlasmaWS281X(Plasma):
    """Class for Plasma light devices in the WS281X/SK6812 family."""

    name = "WS281X"

    options = {
        'pixel_count': int,
        "gpio_pin": int,
        "strip_type": str,
        "channel": int,
        "brightness": int,
        "freq_hz": int,
        "dma": int,
        "invert": bool
    }

    option_order = ("gpio_pin", "strip_type", "channel", "brightness", "freq_hz", "dma", "invert")

    def __init__(self, pixel_count=1, gpio_pin=13, strip_type='WS2812', channel=None, brightness=255, freq_hz=800000, dma=10, invert=False):
        """Initialise WS281X device.

        :param pixel_count: Number of individual RGB LEDs
        :param gpio_pin: BCM GPIO pin for output signal
        :param strip_type: Strip type: one of WS2812 or SK6812
        :param channel: LED channel (0 or 1, or None for automatic)
        :param brightness: Global WS281X LED brightness scale
        :param freq_hz: WS281X output signal frequency (usually 800khz)
        :param dma: DMA channel
        :param invert: Invert signals for NPN-transistor based level shifters

        """
        from rpi_ws281x import PixelStrip, ws

        strip_types = {}
        for t in ws.__dict__:
            if '_STRIP' in t:
                k = t.replace('_STRIP', '')
                v = getattr(ws, t)
                strip_types[k] = v

        strip_type = strip_types[strip_type]

        if channel is None:
            if gpio_pin in [13]:
                channel = 1
            elif gpio_pin in [12, 18]:
                channel = 0

        self._strip = PixelStrip(pixel_count, gpio_pin, freq_hz, dma, invert, brightness, channel, strip_type)
        self._strip.begin()

        Plasma.__init__(self, pixel_count)

    def show(self):
        """Output the buffer."""
        for i in range(self._strip.numPixels()):
            r, g, b, brightness = self._pixels[i]
            self._strip.setPixelColorRGB(i, r, g, b)

        self._strip.show()
Esempio n. 7
0
def clear_strip(strip: PixelStrip):
    """Turn all lights off instantly.

    :return:
    """
    for i in range(strip.numPixels()):
        strip.setPixelColor(i, color(0, 0, 0))
    strip.show()
def dither_fade(
    strip: ws.PixelStrip,
    new_color: Union[ws.Color, np.array],
    leds_to_switch: Optional[Iterable[int]] = None,
    dither_time: float = 1,
):
    """
    Dither in to a new set of colours by switching small batches of pixels.

    Parameters
    ---------
    strip
        the LED strip to animate
    new_color
        Either a single ws.Color or an array of them. Providing one colour acts as an array of that one colour.
    leds_to_switch
        Only dither these LEDs to leave specific elements static.
    dither_time
        the time over which to dither. Do not make this too short
    """

    try:
        iter(new_color)
    except TypeError:
        # this is not iterable, therefore it is one colour.
        # Make an array of that colour.
        new_color = np.array([new_color for _ in range(strip.numPixels())])

    start_time = time.time()
    if leds_to_switch is None:
        leds_to_switch = [i for i in range(strip.numPixels())]
    random.shuffle(leds_to_switch)

    num_leds = len(leds_to_switch)
    # As a rough rule of thumb, it takes 0.005 seconds to switch an LED and render an
    # update. Calculate the group size dynamically to fit into our time budget.

    min_update_time = 0.005
    switches_in_time = int(round(dither_time / min_update_time))
    batch_size = int(round((strip.numPixels() / switches_in_time) + 0.5))
    if batch_size != 1:
        num_batches = int(round((strip.numPixels() / batch_size)))
        batch_size = int(round((strip.numPixels() / num_batches)))

    while leds_to_switch:
        these_leds = [leds_to_switch.pop() for _ in range(batch_size) if leds_to_switch]
        for this_led in these_leds:
            strip.setPixelColor(this_led, new_color[this_led])
        time.sleep(dither_time / (batch_size * num_leds))
        strip.show()

    # Sometimes we go too fast with the switching, as
    # the batching approximation is horrible. If we
    # do, just chill here before moving on
    end_time = time.time()
    time_diff = end_time - start_time
    if time_diff < dither_time:
        time.sleep(dither_time - time_diff)
Esempio n. 9
0
class Solid:
    def __init__(self):
        self.strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA,
                                LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)
        self.strip.begin()

    def start(self):
        for i in range(300):
            self.strip.setPixelColor(i, Color(255, 255, 255))
        self.strip.show()
def color_wipe(strip: ws.PixelStrip, color: ws.Color, wait_ms: float = 50.0):
    """
    Wipe color across display a pixel at a time.

    :param strip: the strip to animate
    :param color: the color to set each pixel to
    :param wait_ms: the time between animating each pixel, in milliseconds
    """
    for i in range(strip.numPixels()):
        strip.setPixelColor(i, color)
        strip.show()
        time.sleep(wait_ms / 1000.0)
def alternate_colors(strip: ws.PixelStrip, colors: Optional[Iterable[ws.Color]] = None):
    """
    Show a set of colours along the strip.

    :param strip: the strip to show the colors on
    :param colors: a list of colors to show
    """
    if colors is None:
        colors = [ws.Color(255, 0, 0), ws.Color(0, 255, 0), ws.Color(0, 0, 255)]
    for i in range(strip.numPixels()):
        strip.setPixelColor(i, colors[i % len(colors)])
    strip.show()
Esempio n. 12
0
def color_wipe(strip: PixelStrip, color: color, wait_ms: int = 50):
    """Wipe color across display a pixel at a time.

    :param strip: PixelStrip object to apply the effect to
    :param color: Color to wipe
    :param wait_ms: blocking time to wait (in ms) before returning
    :return:
    """
    for i in range(strip.numPixels()):
        strip.setPixelColor(i, color)
        strip.show()
        time.sleep(wait_ms / 1000.0)
Esempio n. 13
0
class NeoPixel(object):
    """
    Hanlder fot the rapberrypi and led control
    """

    def __init__(self, pixels):
        # the imports must be hidden since they won't work on pc
        from rpi_ws281x import PixelStrip

        # init the pixel strip
        self.np = PixelStrip(pixels, 18, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)
        self.np.begin()
        self.pixel_count = pixels

    def set(self, index, a, b, g, r):
        """
        Set the a pixel color
        :param index: int, the pixel index
        :param a: int, the alpha value, add for compatibility
        :param b: int, blue value
        :param g:  int, green value
        :param r:  int, red value
        :return:
        """
        from rpi_ws281x import Color
        try:
            # create color and set it
            color = Color(r, g, b)
            self.np.setPixelColor(index, color)
        except IndexError:
            print("error")

    def send(self):
        """
        Show the colors
        :return:
        """
        self.np.show()

    def close(self):
        """
        Set the strip to black and disconnect
        :return:
        """
        from rpi_ws281x import Color

        c = Color(0, 0, 0)
        for idx in range(self.pixel_count):
            self.np.setPixelColor(idx, c)
        self.np.show()
        self.np._cleanup()
        print("Closing PiHandler")
def rainbow(strip: ws.PixelStrip, wait_ms: float = 20.0, iterations: int = 1):
    """
    Draw rainbow that fades across all pixels at once.

    :param strip: the strip to animate
    :param wait_ms: the time between each fading step
    :param iterations: the number of times to play this animation
    """
    for j in range(256 * iterations):
        for i in range(strip.numPixels()):
            strip.setPixelColor(i, get_rainbow_color((i + j) & 255))
        strip.show()
        time.sleep(wait_ms / 1000.0)
Esempio n. 15
0
def rainbow(strip: PixelStrip, wait_ms: int = 20, iterations: int = 1):
    """Draw rainbow that fades across all pixels at once.

    :param strip:
    :param wait_ms:
    :param iterations:
    :return:
    """
    for j in range(256 * iterations):
        for i in range(strip.numPixels()):
            strip.setPixelColor(i, wheel((i + j) & 255))
        strip.show()
        time.sleep(wait_ms / 1000.0)
Esempio n. 16
0
def main():
    parser = argparse.ArgumentParser(
        description='Project an image onto a LED matrix.')
    parser.add_argument('filename',
                        type=str,
                        help='filename of the image to display')
    parser.add_argument('boardsize',
                        type=int,
                        help='the width and height of the LED matrix')
    parser.add_argument('gpionum', type=int, help='the target GPIO pin')
    parser.add_argument('--verbose',
                        '-v',
                        action='store_true',
                        help='enables verbose output')

    args = parser.parse_args()
    global VERBOSE
    VERBOSE = args.verbose
    try:
        from rpi_ws281x import PixelStrip
    except ImportError:

        class PixelStrip():
            """PixelStrip stub."""
            def __init__(self, *args, **kwargs):
                print(
                    "rpi_ws281x not found - this won't actually draw anything."
                )

            def begin(self):
                pass

            def setPixelColorRGB(self, *args):
                pass

            def show(self):
                print("Done mock drawing.")

    np = PixelStrip(args.boardsize**2, args.gpionum, brightness=LED_INTENSITY)
    np.begin()

    my_grid = led_grid.LEDGrid(np, grid.SerpentinePattern.TOP_RIGHT,
                               args.boardsize, args.boardsize)

    image = process_image(args.filename, args.boardsize)
    draw_led_matrix(my_grid, image)
    np.show()
    try:
        terminal_output.print_led_grid(my_grid)
    except:
        traceback.print_exc()
Esempio n. 17
0
def rainbow_cycle(strip: PixelStrip, wait_ms: int = 20, iterations: int = 5):
    """Draw rainbow that uniformly distributes itself across all pixels.

    :param strip:
    :param wait_ms:
    :param iterations:
    :return:
    """
    for j in range(256 * iterations):
        for i in range(strip.numPixels()):
            strip.setPixelColor(
                i, wheel((int(i * 256 / strip.numPixels()) + j) & 255))
        strip.show()
        time.sleep(wait_ms / 1000.0)
Esempio n. 18
0
class Light(Thread):

    def __init__(self, light_state:LightState):
        super().__init__()
        self.state = light_state
        self.periodic = None
        self.refresh_period_or_duty_cycle()

        self.strip = PixelStrip(self.state.get_num_pixels(), 18)

    async def loop(self):
        while True:
            await self.periodic.wait_for_period_boundary()
            self.set_first_half_of_period()
            await self.periodic.wait_for_semi_period_boundary()
            self.set_second_half_of_period()

    def set_first_half_of_period(self):
        if not self.state.get_power():
            self.set_off()
        else:
            self.set_on()

    def set_second_half_of_period(self):
        if not self.state.get_power() or self.state.get_blink():
            self.set_off()
        else:
            self.set_on()

    def set_on(self):
        self.strip.setBrightness(self.state.get_brightness())
        for pixel in range(self.state.get_num_pixels()):
            self.strip.setPixelColorRGB(pixel, self.state.get_red(), self.state.get_green(), self.state.get_blue())
        self.strip.show()

    def set_off(self):
        for pixel in range(self.state.get_num_pixels()):
            self.strip.setPixelColorRGB(pixel, 0, 0, 0)
        self.strip.show()

    def refresh_period_or_duty_cycle(self):
        self.periodic = Periodic(
            period_sec=self.state.get_period(),
            semi_period_percent=self.state.get_duty_cycle()
        )

    def run(self):
        self.strip.begin()
        asyncio.run(self.loop())
Esempio n. 19
0
    def set_color(self, color):
        rgb = int(color, 16)
        r = int(rgb / 256 / 256)
        rgb = rgb - r * 256 * 256
        g = int(rgb / 256)
        b = rgb - g * 256
        # Create NeoPixel object with appropriate configuration.
        strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA,
                           LED_INVERT, LED_BRIGHTNESS)
        # Intialize the library (must be called once before other functions).
        strip.begin()

        for i in range(0, strip.numPixels(), 1):
            strip.setPixelColor(i, Color(g, r, b))
            strip.show()
Esempio n. 20
0
def theater_chase_rainbow(strip: PixelStrip, wait_ms: int = 50):
    """Rainbow movie theater light style chaser animation.

    :param strip:
    :param wait_ms:
    :return:
    """
    for j in range(256):
        for q in range(3):
            for i in range(0, strip.numPixels(), 3):
                strip.setPixelColor(i + q, wheel((i + j) % 255))
            strip.show()
            time.sleep(wait_ms / 1000.0)
            for i in range(0, strip.numPixels(), 3):
                strip.setPixelColor(i + q, 0)
Esempio n. 21
0
class Fade:
    def __init__(self):
        self.gammaTable = [
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4,
            5, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 11, 11, 11,
            12, 12, 13, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19,
            20, 21, 21, 22, 22, 23, 23, 24, 25, 25, 26, 27, 27, 28, 29, 29, 30,
            31, 31, 32, 33, 34, 34, 35, 36, 37, 37, 38, 39, 40, 40, 41, 42, 43,
            44, 45, 46, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
            60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 76, 77,
            78, 79, 80, 81, 83, 84, 85, 86, 88, 89, 90, 91, 93, 94, 95, 96, 98,
            99, 100, 102, 103, 104, 106, 107, 109, 110, 111, 113, 114, 116,
            117, 119, 120, 121, 123, 124, 126, 128, 129, 131, 132, 134, 135,
            137, 138, 140, 142, 143, 145, 146, 148, 150, 151, 153, 155, 157,
            158, 160, 162, 163, 165, 167, 169, 170, 172, 174, 176, 178, 179,
            181, 183, 185, 187, 189, 191, 193, 194, 196, 198, 200, 202, 204,
            206, 208, 210, 212, 214, 216, 218, 220, 222, 224, 227, 229, 231,
            233, 235, 237, 239, 241, 244, 246, 248, 250, 252, 255
        ]
        self.strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA,
                                LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)
        self.strip.begin()
        self.cols = []
        self.hues = np.arange(360, step=10)
        for i in range(36):
            self.cols.append(hsv2rgb(self.hues[i] / 360, 1, 1))

    def start(self):
        while True:
            for col in self.cols:
                for i in range(100):
                    b = i * (1 / 100)
                    color = Color(self.gammaTable[int(col[0] * b)],
                                  self.gammaTable[int(col[1] * b)],
                                  self.gammaTable[int(col[2] * b)])
                    for j in range(LED_COUNT):
                        self.strip.setPixelColor(j, color)
                    self.strip.show()
                for i in range(100, 0, -1):
                    b = i * (1 / 100)
                    color = Color(self.gammaTable[int(col[0] * b)],
                                  self.gammaTable[int(col[1] * b)],
                                  self.gammaTable[int(col[2] * b)])
                    for j in range(LED_COUNT):
                        self.strip.setPixelColor(j, color)
                    self.strip.show()
Esempio n. 22
0
class Quicksort:
    def partition(self, arr, start, end):
        pivot = arr[end]
        i = start
        for j in range(start, end):
            if arr[j] <= arr[
                    end]:  # if arr[j] is less than arr[i] we swap the values
                arr[i], arr[j] = arr[j], arr[i]
                # cols = hueToRgb(arr)
                col = hsv2rgb(arr[j] / 360, 1, 1)
                col2 = hsv2rgb(arr[i] / 360, 1, 1)
                self.strip.setPixelColor(j, Color(col[0], col[1], col[2]))
                self.strip.show()
                self.strip.setPixelColor(i, Color(col2[0], col2[1], col2[2]))
                i = i + 1
                self.strip.show()
        arr[i], arr[end] = arr[end], arr[i]
        col = hsv2rgb(arr[i] / 360, 1, 1)
        col2 = hsv2rgb(arr[end] / 360, 1, 1)
        self.strip.setPixelColor(i, Color(col[0], col[1], col[2]))
        self.strip.show()
        self.strip.setPixelColor(end, Color(col2[0], col2[1], col2[2]))
        self.strip.show()
        return i

    def quicksort(self, arr, start, end):
        if start < end:
            index = self.partition(arr, start, end)
            self.quicksort(arr, start, index - 1)
            self.quicksort(arr, index + 1, end)

    def __init__(self):
        self.strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA,
                                LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)
        self.strip.begin()

    def start(self):
        while True:
            hues = np.arange(300)
            random.shuffle(hues)
            cols = hueToRgb(hues)
            for k in range(300):
                color = Color(cols[k][0], cols[k][1], cols[k][2])
                self.strip.setPixelColor(k, color)
            self.strip.show()
            self.quicksort(hues, 0, len(hues) - 1)
Esempio n. 23
0
def run():
    prev_animation = None
    prev_brightness = None
    strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT,
                       LED_BRIGHTNESS, LED_CHANNEL, LED_STRIP)
    strip.begin()

    threading.Thread(target=app.run).start()
    print('Press Ctrl-C to quit.')
    len_animations = None
    try:
        while True:
            if len(curr_animations) != len_animations:
                len_animations = len(curr_animations)
                clear(strip)

                generators = []
                for animation in curr_animations:
                    generators.append(animation(VStrip(strip)))

            if curr_brightness != prev_brightness:
                strip.setBrightness(curr_brightness)
                prev_brightness = curr_brightness

            vstrips = []
            for gen in generators:
                vstrips.append(next(gen))
                # vstrip.reverse()

            for pos in range(strip.numPixels()):
                col = np.array([0., 0., 0.])
                transparency = 1
                for v in vstrips:
                    cur_col = np.array(v.getPixelColor(pos))
                    col += cur_col[:3] * transparency
                    transparency *= cur_col[3]

                col = np.maximum(
                    np.minimum(np.array(np.floor(col), dtype=np.int), 255), 0)
                strip.setPixelColor(pos, Color(*col.tolist()))

            strip.show()

    except KeyboardInterrupt:
        clear(strip)
def theater_chase(
    strip: ws.PixelStrip, color: ws.Color, wait_ms: float = 50.0, iterations: int = 10
):
    """
    Movie theater light style chaser animation.

    :param strip: the strip to animate
    :param color: the color to set each pixel to
    :param wait_ms: the time between animating each pixel, in milliseconds
    :param iterations: the number of times this animation will play
    """
    for j in range(iterations):
        for q in range(3):
            for i in range(0, strip.numPixels(), 3):
                strip.setPixelColor(i + q, color)
            strip.show()
            time.sleep(wait_ms / 1000.0)
            for i in range(0, strip.numPixels(), 3):
                strip.setPixelColor(i + q, 0)
Esempio n. 25
0
class RpiWs281xLedstrip(AbstractLight):

    def __init__(self) -> None:
        super().__init__(led_count=LED_COUNT)
        
        self.pixel_strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)
        self.pixel_strip.begin()

    def write(self):
        assert self.pixel_strip.numPixels() == len(self.leds)

        # Update the value for each of the pixels in the strip
        for i in range(startLED, self.pixel_strip.numPixels()):
            [red, green, blue, brightness] = self.leds[i]
            colors = (int(c * brightness * 255) for c in (red, green, blue))
            self.pixel_strip.setPixelColorRGB(i, *colors, 255)

        # Flush the new values to the strip
        self.pixel_strip.show()
Esempio n. 26
0
class RaspberryPiHAL:
    def __init__(self, config):
        self.num_pixels = config['LedMatrix']['columns'] * config['LedMatrix'][
            'stride']
        self.strip = PixelStrip(self.num_pixels, LED_PIN, LED_FREQ_HZ, LED_DMA,
                                LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)
        self.strip.begin()

    def init_display(self, num_pixels=64):
        self.clear_display()

    def clear_display(self):
        c = Color(0, 0, 0)
        for i in range(self.num_pixels):
            self.strip.setPixelColor(i, c)
        self.strip.show()

    def update_display(self, num_modified_pixels):
        if not num_modified_pixels:
            return
        self.strip.show()

    def put_pixel(self, addr, r, g, b):
        self.strip.setPixelColor(addr % self.num_pixels, Color(r, g, b))

    def reset(self):
        self.clear_display()

    def process_input(self):
        #TODO: implement
        return 0

    def set_rtc(self, t):
        #Not relevant
        pass

    def set_auto_time(self, enable=True):
        #Not relevant
        pass

    def suspend_host(self, restart_timeout_seconds):
        #Not relevant
        pass
Esempio n. 27
0
def theater_chase(strip: PixelStrip,
                  color: color,
                  wait_ms: int = 50,
                  iterations: int = 10):
    """Movie theater light style chaser animation.

    :param strip:
    :param color:
    :param wait_ms:
    :param iterations:
    :return:
    """
    for j in range(iterations):
        for q in range(3):
            for i in range(0, strip.numPixels(), 3):
                strip.setPixelColor(i + q, color)
            strip.show()
            time.sleep(wait_ms / 1000.0)
            for i in range(0, strip.numPixels(), 3):
                strip.setPixelColor(i + q, 0)
Esempio n. 28
0
class LedManager(object):
    # TODO: - Log and document this class

    # LED strip configuration:
    __LED_COUNT = 3         # Number of LED pixels.
    __LED_PIN = 18          # GPIO pin connected to the pixels (must support PWM!).
    __LED_FREQ_HZ = 800000  # LED signal frequency in hertz (usually 800khz)
    __LED_DMA = 10          # DMA channel to use for generating signal (try 10)
    __LED_BRIGHTNESS = 255  # Set to 0 for darkest and 255 for brightest
    __LED_INVERT = False    # True to invert the signal (when using NPN transistor level shift)
    __LED_CHANNEL = 0
    __LED_STRIP = ws.WS2812_STRIP

    __instance = None

    def __init__(self):
        if LedManager.__instance is None:
            LedManager.__instance = self
            self.strip = PixelStrip(self.__LED_COUNT, self.__LED_PIN, self.__LED_FREQ_HZ, self.__LED_DMA,
                                    self.__LED_INVERT, self.__LED_BRIGHTNESS, self.__LED_CHANNEL, self.__LED_STRIP)
            self.strip.begin()
        else:
            raise Exception("This class is a Singleton")

    @staticmethod
    def get_instance():
        """
        :rtype: LedManager
        """
        if LedManager.__instance is None:
            LedManager()
        return LedManager.__instance

    # Define function that colors all LEDs of the given color.
    def color_wipe(self, led_color, wait_ms=50):
        for i in range(0, self.strip.numPixels()):
            self.strip.setPixelColor(i, led_color.value)
            self.strip.show()
            time.sleep(wait_ms / 1000.0)
Esempio n. 29
0
class LedStrip(object):
    def __init__(self):
        self.status = 'off'
        self.strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)
        self.strip.begin()
        self.set_color(BLACK)

    def toggle_light(self):
        if self.status == STATUS_ON:
            self.set_color(BLACK)
            self.status = STATUS_OFF
        else:
            self.set_color(SOFT_WHITE)
            self.status = STATUS_ON

    def set_color(self, color, wait_ms=200):
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(i, color)
        self.strip.show()
        time.sleep(wait_ms / 1000)

    def get_status(self):
        return self.status
Esempio n. 30
0
class PiHandler(object):
    """
    Hanlder fot the rapberrypi and led control
    """
    def __init__(self, pixels):
        # the imports must be hidden since they won't work on pc
        from rpi_ws281x import PixelStrip

        # init the pixel strip
        self.np = PixelStrip(pixels, PIN)
        self.np.begin()
        self.pixel_count = pixels
        self.is_stopped = False

    def set(self, index, c, b, g, r):
        from rpi_ws281x import Color

        if index is not None and index < self.pixel_count:
            # scale the rgb value by the intensity
            r = scale(r, c)
            g = scale(g, c)
            b = scale(b, c)
            # create color and set it
            color = Color(r, g, b)
            self.np.setPixelColor(index, color)

    def send(self):

        self.np.show()

    def on_loop(self):
        raise NotImplementedError

    def close(self):
        for index in range(self.pixel_count):
            self.np.setPixelColor(index, 0)
        self.np.show()