Esempio n. 1
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()
 def start_strip(self):
     """
     Start PixelStrip object
     :returns strip: (rpi_ws281x.PixelStrip) The initialised strip object
     """
     self._logger.info("Initialising LED strip")
     try:
         strip = PixelStrip(
             num=int(self.strip_settings["count"]),
             pin=int(self.strip_settings["pin"]),
             freq_hz=int(self.strip_settings["freq_hz"]),
             dma=int(self.strip_settings["dma"]),
             invert=bool(self.strip_settings["invert"]),
             brightness=int(self.strip_settings["brightness"]),
             channel=int(self.strip_settings["channel"]),
             strip_type=constants.STRIP_TYPES[self.strip_settings["type"]],
         )
         strip.begin()
         self._logger.info("Strip successfully initialised")
         return strip
     except Exception as e:  # Probably wrong settings...
         self._logger.error(repr(e))
         self._logger.error(
             "Strip failed to initialize, no effects will be run.")
         raise StripFailedError("Error intitializing strip")
def pixel_strip():
    """
    Initialized and started PixelStrip fixture
    """
    ps = PixelStrip(NUM_PIXELS, 0)
    ps.begin()
    return ps
Esempio n. 4
0
def setup_strip():
    global LED_BRIGHTNESS
    global which_effect
    which_effect = False
    # LED strip configuration:
    LED_COUNT = 300  # Number of LED pixels.
    LED_PIN = 18  # GPIO pin connected to the pixels (18 uses PWM!).
    # LED_PIN        = 10      # GPIO pin connected to the pixels (10 uses SPI /dev/spidev0.0).
    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  # set to '1' for GPIOs 13, 19, 41, 45 or 53
    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).
    logger.debug(f"Setting up strip")
    strip.begin()
    clear_strip(strip)
    return strip
Esempio n. 5
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. 6
0
def setup_led_strips():
    # Create PixelStrip object with appropriate configuration
    global strip
    strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT,
                       LED_BRIGHTNESS, LED_CHANNEL, LED_STRIP)
    # Initialize the library (must be called once before other functions)
    strip.begin()
 def start_strip(self):
     """
     Start PixelStrip object
     :returns rpi_ws281x.PixelStrip
     """
     self._logger.info("Initialising LED strip")
     strip_settings = self.settings['strip']
     try:
         strip = PixelStrip(
             num=strip_settings['led_count'],
             pin=strip_settings['led_pin'],
             freq_hz=strip_settings['led_freq_hz'],
             dma=strip_settings['led_dma'],
             invert=strip_settings['led_invert'],
             brightness=strip_settings['led_brightness'],
             channel=strip_settings['led_channel'],
             strip_type=STRIP_TYPES[strip_settings['strip_type']])
         strip.begin()
         self._logger.info("Strip object successfully initialised")
         return strip
     except Exception as e:  # Probably wrong settings...
         self._logger.error(
             "Strip failed to initialize, no effects will be run.")
         self._logger.error("Please check your settings.")
         self._logger.error("Here's the exception: {}".format(e))
         return None
Esempio n. 8
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. 9
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. 10
0
class Canvas():
    def __init__(self):
        # strip = None
        # self.DotCount = LED_COUNT
        # 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()
        self.DotCount = self.strip.numPixels()

    def FillSolid(self, color):
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(i, color)

    # def DrawPixels(self, position, size, color):
    #     dot = int(position)
    #     if dot < 0:return
    #     if dot >= self.DotCount:return
    #     # print("{dot:.2f}, {position:.2f}, {size:.2f}".format(dot=dot, position=position, size=size))
    #     self.strip.setPixelColor(dot, color)
    def DrawPixels(self, position, size, color):
        left_dot = int(position - size / 2)
        right_dot = int(position + size / 2)
        if right_dot < 0: return
        if left_dot < 0:
            left_dot = 0
        if left_dot >= self.DotCount: return
        if right_dot >= self.DotCount:
            right_dot = self.DotCount
        # print("{dot:.2f}, {position:.2f}, {size:.2f}".format(dot=dot, position=position, size=size))
        for dot in range(left_dot, right_dot + 1):
            self.strip.setPixelColor(dot, color)
Esempio n. 11
0
    class __LedCore:
        def __init__(self):
            # Create NeoPixel object with appropriate configuration.
            self.strip = PixelStrip(
                settings.LED_COUNT,
                settings.LED_PIN,
                settings.LED_FREQ_HZ,
                settings.LED_DMA,
                settings.LED_INVERT,
                settings.LED_BRIGHTNESS,
                settings.LED_CHANNEL,
            )
            # Intialize the library (must be called once before other functions).
            self.strip.begin()

            self.thread = None
            self.strip_actions = StripActions()

        def strip_action(self, name, **kwargs):
            if (issubclass(type(self.thread), StoppableThread)
                    and self.thread.is_alive() and not self.thread.stopped()):
                self.thread.stop()
                self.thread.join()
            self.thread = getattr(self.strip_actions, name)(self.strip,
                                                            **kwargs)
            return self.thread
Esempio n. 12
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. 13
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()
Esempio n. 14
0
def init():
    global strip
    LED_COUNT = cfg["WS8211"].getint("count", 6)
    LED_PIN = cfg["WS8211"].getint("pin", 12)
    LED_FREQ_HZ = cfg["WS8211"].getint("frequence", 800000)
    LED_DMA = cfg["WS8211"].getint("dma", 10)
    LED_INVERT = cfg["WS8211"].getboolean("invert", False)
    LED_BRIGHTNESS = cfg["WS8211"].getint("brightness", 50)
    LED_CHANNEL = cfg["WS8211"].getint("channel", 0)
    strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT,
                       LED_BRIGHTNESS, LED_CHANNEL)
    strip.begin()
Esempio n. 15
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")
Esempio n. 16
0
class Steps(list):
    def __init__(self):
        # 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()

        for i, led_counter in enumerate(NUMBER_OF_LEDS):
            # get last led
            start = 0 if i == 0 else (self[-1][-1] + 1)
            # define step 
            step = Step(self.strip, start, start + led_counter)
            self.append(step)
    
    def __len__(self):
        return sum(NUMBER_OF_LEDS)

    def off(self, step_ms=0, led_ms=0):
        for step in self:
            step.off(led_ms)
        wait(step_ms)

    def color_test(self):
        for i, step in enumerate(self):
            color = Color(255, 0, 0) if i % 2 == 0 else Color(0, 255, 0)
            for led in step:
                self.strip.setPixelColor(led, color)
                self.strip.show()

    def pong(self, ms=10):
        for step in self:
            step.pong_init()

        while True:
            for step in self:
                step.pong_loop(ms=0)
            wait(ms)
    
    def rainbow(self, wait_ms=20, iterations=1):
        """Draw rainbow that fades across all pixels at once."""
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(i, wheel(i & 255))
            self.strip.show()
            wait(wait_ms)

    def rainbowCycle(self, wait_ms=20, iterations=5):
        """Draw rainbow that uniformly distributes itself across all pixels."""
        for j in range(256*iterations):
            for i in range(self.strip.numPixels()):
                self.strip.setPixelColor(i, wheel((int(i * 256 / self.strip.numPixels()) + j) & 255))
            self.strip.show()
            wait(wait_ms)
Esempio n. 17
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. 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 setup():
    global ws2812, _is_setup

    if _is_setup:
        return

    ws2812 = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL, LED_GAMMA)

    ws2812.begin()

    set_layout(HAT)

    atexit.register(_clean_shutdown)

    _is_setup = True
Esempio n. 20
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. 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
    def create(size, name="neopixel"):
        pin = settings["glow"]["neopixel"]["pin"]
        freq_hz = settings["glow"]["neopixel"]["freq_hz"]
        dma = settings["glow"]["neopixel"]["dma"]
        invert = settings["glow"]["neopixel"]["invert"]
        brightness = settings["glow"]["neopixel"]["brightness"]
        channel = settings["glow"]["neopixel"]["channel"]

        strip = None
        if name.lower() == "neopixel":
            # Create NeoPixel object with appropriate configuration.
            strip = PixelStrip(size, pin, freq_hz, dma, invert, brightness,
                               channel)
            # Intialize the library (must be called once before other functions).
            strip.begin()

        return strip
Esempio n. 23
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. 24
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)
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
def action(deviceName):
    strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT,
                       LED_BRIGHTNESS, LED_CHANNEL)
    strip.begin()
    if deviceName == 'white':
        colorWipe(strip, color(255, 255, 255))
        return redirect('/', code=302)
    if deviceName == 'off':
        colorWipe(strip, color(0, 0, 0))
        return redirect('/', code=302)
    if deviceName == 'red':
        colorWipe(strip, color(255, 0, 0))
        return redirect('/', code=302)
    if deviceName == 'purple':
        colorWipe(strip, color(75, 130, 0))
        return redirect('/', code=302)
    if deviceName == 'yellow':
        colorWipe(strip, color(255, 0, 103))
        return redirect('/', code=302)
Esempio n. 27
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. 28
0
def main():
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind((LISTEN_IP, LISTEN_PORT))

    matrix = list()
    for i in range(SIZE_W * SIZE_H * 3):
        matrix.append(0)

    pixels = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)
    pixels.begin()
    display_clear(pixels)

    try:
        while True:
            wait_for_data(sock, matrix)
            display_data(matrix, pixels)
    except KeyboardInterrupt:
        display_clear(pixels)
        sock.close()
Esempio n. 29
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. 30
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. 31
0
    for j in range(256*iterations):
        for i in range(strip.numPixels()):
            strip.setPixelColor(i, wheel(((i * 256 / strip.numPixels()) + j) & 255))
        strip.show()
        time.sleep(wait_ms/1000.0)

# Main loop:
if __name__ == '__main__':
    # Create NeoPixel object with appropriate configuration.
    #strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS)
    if __version__ == "legacy":
        strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)
    else:
        strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL, LED_GAMMA)# Intialize the library (must be called once before other functions).

    strip.begin()

    ## Color wipe animations.
    colorWipe(strip, Color(127, 0, 0), WAIT_MS)  # Red wipe
    colorWipe(strip, Color(0, 127, 0), WAIT_MS)  # Green wipe
    colorWipe(strip, Color(0, 0, 127), WAIT_MS)  # Blue wipe
    colorWipe(strip, Color(0, 0, 0), WAIT_MS)  # Off wipe

    ## Rainbow animations.
    #rainbow(strip)
    #rainbowCycle(strip)
    #colorWipe(strip, Color(0, 0, 0))  # Off wipe

    while True:
        try:
            data = raw_input()