Ejemplo n.º 1
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)
Ejemplo n.º 2
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()
Ejemplo n.º 3
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)
Ejemplo n.º 4
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()
Ejemplo n.º 5
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)
Ejemplo n.º 6
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)
Ejemplo n.º 7
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
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)
Ejemplo n.º 9
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)
Ejemplo n.º 10
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)
Ejemplo n.º 11
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
Ejemplo n.º 12
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()
Ejemplo n.º 13
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)
Ejemplo n.º 14
0
#!/usr/bin/python3
# Set the pixels back to off

from rpi_ws281x import PixelStrip, Color
import time

LEDCOUNT = 2  # Number of LEDs
GPIOPIN = 18
FREQ = 800000
DMA = 5
INVERT = True  # Invert required when using inverting buffer
BRIGHTNESS = 255

strip = PixelStrip(LEDCOUNT, GPIOPIN, FREQ, DMA, INVERT, BRIGHTNESS)
# Intialize the library (must be called once before other functions).
strip.begin()

# First LED white
strip.setPixelColor(0, Color(0, 0, 0))
strip.setPixelColor(1, Color(0, 0, 0))
strip.show()
Ejemplo n.º 15
0

def xy_to_arrayIndex(x, y):
    if x % 2 == 0:
        return (x * 8) + y
    else:
        return (x * 8) + (8 - y - 1)


# Main program logic follows:
if __name__ == "__main__":
    # Intialize the library (must be called once before other functions).
    strip.begin()

    # step 1 - light single LED
    strip.setPixelColor(xy_to_arrayIndex(0, 0), Color(100, 0, 0))
    strip.show()
    time.sleep(50 / 1000)
    strip.setPixelColor(xy_to_arrayIndex(1, 1), Color(100, 0, 0))
    strip.show()
    time.sleep(50 / 1000)
    strip.setPixelColor(xy_to_arrayIndex(2, 2), Color(100, 0, 0))
    strip.show()
    time.sleep(50 / 1000)
    strip.setPixelColor(xy_to_arrayIndex(3, 3), Color(100, 0, 0))
    strip.show()
    time.sleep(50 / 1000)
    strip.setPixelColor(xy_to_arrayIndex(4, 4), Color(100, 0, 0))
    strip.show()
    time.sleep(50 / 1000)
    strip.setPixelColor(xy_to_arrayIndex(5, 5), Color(100, 0, 0))
class LEDController:
    def __init__(self, LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT,
                 LED_BRIGHTNESS, LED_CHANNEL, LED_STRIP):
        self._strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA,
                                 LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL,
                                 LED_STRIP)
        self._strip.begin()
        self._step = 0.5
        self._start = 0

    def color_wipe(self, color, wait_ms=50):
        for i in range(self._strip.numPixels()):
            self._strip.setPixelColor(i, color)
            time.sleep(wait_ms / 1000.0)
        self._strip.show()
        #time.sleep(wait_ms / 1000.0)

    def idle_lighting(self):
        self.color_wipe(Color(50, 50, 50), 0)

    def listening_lighting(self):
        #proximity = ProximityController.get_proximity_data()
        self.color_wipe(Color(150, 150, 150), 0)

    def map_range(self, x, inLow, inHigh, outLow, outHigh):
        inRange = inHigh - inLow
        outRange = outHigh - outLow
        inScale = (x - inLow) / inRange
        return outLow + (inScale * outRange)

    def breathing_effect(self):
        while responding:
            duty = self.map_range(math.sin(self._start), -1, 1, 0, 150)
            self._start += self._step
            #self.color_wipe(Color(0,0,0,int(duty)),0)
            self.color_wipe(Color(int(duty), int(duty), int(duty)), 0)
            time.sleep(0.05)

    def alternate_lighting(self, color, wait_ms=50):
        for i in range(0, self._strip.numPixels(), 2):
            self._strip.setPixelColor(i, color)
            time.sleep(wait_ms / 1000.0)
        self._strip.show()
        time.sleep(1)

    def greeting_effetct(self):
        brightness = self.map_range(-distance, -4000, 0, 0, 150)
        self.color_wipe(
            Color(int(brightness), int(brightness), int(brightness), 0), 0)

    def wave_effect(self, color=Color(50, 50, 50), wait_ms=5):
        for i in range(0, self._strip.numPixels(), 5):
            self.switch_off()
            for j in range(0, 5):
                self._strip.setPixelColor(i + j, color)
                time.sleep(wait_ms / 1000.0)
            self._strip.show()

        for i in range(self._strip.numPixels(), -1, -5):
            self.switch_off()
            for j in range(0, min(5, i)):
                self._strip.setPixelColor(i - j, color)
                time.sleep(wait_ms / 1000.0)
            self._strip.show()

    def switch_off(self):
        self.color_wipe(Color(0, 0, 0), 0)
Ejemplo n.º 17
0
LED_CHANNEL = 0  # set to '1' for GPIOs 13, 19, 41, 45 or 53


def wheel(pos):
    """Generate rainbow colors across 0-255 positions."""
    if pos < 85:
        return Color(pos * 3, 255 - pos * 3, 0)
    elif pos < 170:
        pos -= 85
        return Color(255 - pos * 3, 0, pos * 3)
    else:
        pos -= 170
        return Color(0, pos * 3, 255 - pos * 3)


if __name__ == '__main__':
    # Process arguments
    parser = argparse.ArgumentParser()
    parser.add_argument('number', help='anchor number')
    args = parser.parse_args()

    print args.number

    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).
    strip.begin()
    NUM_ANCHORS = 10
    strip.setPixelColor(0, wheel(255 / NUM_ANCHORS * (int(args.number) - 1)))
    strip.show()
Ejemplo n.º 18
0
class Ledstrip:
    def __init__(self):
        self.onGoingTask = None
        self.cancelTask = False
        self.brightness = constants.LED_BRIGHTNESS
        self.pixels = PixelStrip(constants.LED_COUNT, constants.LED_PIN,
                                 constants.LED_FREQ_HZ, constants.LED_DMA,
                                 constants.LED_INVERT,
                                 constants.LED_BRIGHTNESS,
                                 constants.LED_CHANNEL, constants.LED_STRIP)
        self.pixels.begin()
        LedUtil.clear(self.pixels)
        self.pixels.setPixelColor(0, Color(255, 255, 255, 255))
        self.pixels.show()

        print("Controlling ledstrip on pin ", constants.LED_PIN)

    def pixel_rainbow_colors(self, args):
        wait, isFloat = Util.floatTryParse(args["wait"])
        loop_forever, isBool = Util.boolTryParse(args["loop_forever"])
        if (isFloat and isBool):
            self.__execute_task(
                LedUtil.rainbow_colors,
                (self.pixels, lambda: self.cancelTask, wait, loop_forever))

    def pixel_rainbow_cycle(self, args):
        loop_forever, isBool = Util.boolTryParse(args["loop_forever"])
        wait, isFloat = Util.floatTryParse(args["wait"])
        loop, isInt = Util.intTryParse(args["loop"])
        if (isBool and isFloat and isInt):
            self.__execute_task(LedUtil.rainbow_cycle,
                                (self.pixels, lambda: self.cancelTask, wait,
                                 loop, loop_forever))

    def pixel_rainbow_cycle_successive(self, args):
        wait, isFloat = Util.floatTryParse(args["wait"])
        if (isFloat):
            self.__execute_task(LedUtil.rainbow_cycle_successive,
                                (self.pixels, lambda: self.cancelTask, wait))

    def pixel_brightness_decrease(self, args):
        wait, isFloat = Util.floatTryParse(args["wait"])
        step, isInt = Util.intTryParse(args["step"])
        if (isFloat and isInt):
            self.__execute_task(
                LedUtil.brightness_decrease,
                (self.pixels, lambda: self.cancelTask, wait, step))

    def pixel_blink_color(self, args):
        color, isColor = Util.colorTryParse(args["color"])
        wait, isFloat = Util.floatTryParse(args["wait"])
        blink_time, isInt = Util.intTryParse(args["blink_time"])
        if (isColor and isFloat and isInt):
            self.__execute_task(LedUtil.blink_color,
                                (self.pixels, lambda: self.cancelTask,
                                 blink_time, wait, color))

    def pixel_appear_from_back(self, args):
        color, isColor = Util.colorTryParse(args["color"])
        wait, isFloat = Util.floatTryParse(args["wait"])
        size, isInt = Util.intTryParse(args["size"])
        if (isColor and isFloat and isInt):
            self.__execute_task(
                LedUtil.appear_from_back,
                (self.pixels, lambda: self.cancelTask, color, wait, size))

    def pixel_color_wipe(self, args):
        color, isColor = Util.colorTryParse(args["color"])
        wait, isFloat = Util.floatTryParse(args["wait"])
        should_clear, isBool = Util.boolTryParse(args["should_clear"])
        if (isColor and isFloat and isBool):
            self.__execute_task(LedUtil.color_wipe,
                                (self.pixels, lambda: self.cancelTask, wait,
                                 color, should_clear))

    def pixel_color_wipe_cycle(self, args):
        color, isColor = Util.colorTryParse(args["color"])
        wait, isFloat = Util.floatTryParse(args["wait"])
        fade_step, isInt = Util.intTryParse(args["fade_step"])
        loop_forever, isBool = Util.boolTryParse(args["loop_forever"])
        if (isColor and isFloat and isInt and isBool):
            self.__execute_task(LedUtil.color_wipe_cycle,
                                (self.pixels, lambda: self.cancelTask, wait,
                                 color, fade_step, loop_forever))

    def pixel_theater_chase(self, args):
        color, isColor = Util.colorTryParse(args["color"])
        wait, isFloat = Util.floatTryParse(args["wait"])
        is_rainbow, isBool = Util.boolTryParse(args["is_rainbow"])
        if (isColor and isFloat and isBool):
            self.__execute_task(LedUtil.theaterChase,
                                (self.pixels, lambda: self.cancelTask, color,
                                 wait, is_rainbow))

    def pixel_color_wipe_rainbow(self, args):
        wait, isFloat = Util.floatTryParse(args["wait"])
        fade_step, isInt = Util.intTryParse(args["fade_step"])
        color_step, isInt2 = Util.intTryParse(args["color_step"])
        if (isFloat and isInt and isInt2):
            self.__execute_task(LedUtil.color_wipe_rainbow,
                                (self.pixels, lambda: self.cancelTask, wait,
                                 fade_step, color_step))

    def pixel_breathing(self, args):
        color, isColor = Util.colorTryParse(args["color"])
        move_factor, isFloat = Util.floatTryParse(args["move_factor"])
        if (isFloat and isColor):
            self.__execute_task(
                LedUtil.breathing,
                (self.pixels, lambda: self.cancelTask, color, move_factor))

    def pixel_breathing_lerp(self, args):
        color_to, isColor1 = Util.colorTryParse(args["color_to"])
        color_from, isColor2 = Util.colorTryParse(args["color_from"])
        move_factor, isFloat = Util.floatTryParse(args["move_factor"])
        if (isColor1 and isColor2 and isFloat):
            self.__execute_task(LedUtil.breathing_lerp,
                                (self.pixels, lambda: self.cancelTask,
                                 color_from, color_to, move_factor))

    def pixel_breathing_rainbow(self, args):
        move_factor, isFloat = Util.floatTryParse(args["move_factor"])
        color_step, isInt = Util.intTryParse(args["color_step"])
        if (isInt and isFloat):
            self.__execute_task(LedUtil.breathing_rainbow,
                                (self.pixels, lambda: self.cancelTask,
                                 color_step, move_factor))

    def pixel_fireworks(self, args):
        size, isInt = Util.intTryParse(args["size"])
        color, isColor = Util.colorTryParse(args["color"])
        is_rainbow, isBool = Util.boolTryParse(args["is_rainbow"])
        number_of_fireworks, isInt1 = Util.intTryParse(
            args["number_of_fireworks"])
        chance_of_explosion, isInt2 = Util.intTryParse(
            args["chance_of_explosion"])
        fade_step, isInt3 = Util.intTryParse(args["fade_step"])
        firework_fade, isInt4 = Util.intTryParse(args["firework_fade"])
        if (isColor and isBool and isInt and isInt1 and isInt2 and isInt3
                and isInt4):
            self.__execute_task(
                LedUtil.fireworks,
                (self.pixels, lambda: self.cancelTask, size, color, is_rainbow,
                 number_of_fireworks, chance_of_explosion, fade_step,
                 firework_fade))

    def pixel_labyrinth(self, args):
        wait, isFloat = Util.floatTryParse(args["wait"])
        color, isColor = Util.colorTryParse(args["color"])
        contact_color, isColor2 = Util.colorTryParse(args["contact_color"])
        count, isInt = Util.intTryParse(args["count"])
        turn_chance, isInt2 = Util.intTryParse(args["turn_chance"])
        if (isColor and isColor2 and isFloat and isInt and isInt2):
            self.__execute_task(LedUtil.labyrinth,
                                (self.pixels, lambda: self.cancelTask, wait,
                                 count, turn_chance, color, contact_color))

    def pixel_color_pair(self, args):
        wait, isFloat = Util.floatTryParse(args["wait"])
        color1, isColor1 = Util.colorTryParse(args["color1"])
        color2, isColor2 = Util.colorTryParse(args["color2"])
        size1, isInt1 = Util.intTryParse(args["size1"])
        size2, isInt2 = Util.intTryParse(args["size2"])
        with_animation, isBool = Util.boolTryParse(args["with_animation"])
        fade_step, isInt = Util.intTryParse(args["fade_step"])
        if (isColor1 and isColor2 and isFloat and isInt1 and isInt2 and isInt
                and isBool):
            self.__execute_task(
                LedUtil.color_pair,
                (self.pixels, lambda: self.cancelTask, wait, color1, color2,
                 size1, size2, with_animation, fade_step))

    def set_brightness(self, args):
        brightness, isInt = Util.intTryParse(args["brightness"])
        if (isInt):
            self.brightness = brightness
            self.pixels.setBrightness(brightness)
            self.pixels.show()

    def set_settings(self, args):
        self.__cancel_task()

        led_pixel_count, isInt = Util.intTryParse(args["led_pixel_count"])
        if (isInt):
            self.led_count = led_pixel_count
            self.led_type = args["led_type"]
            ledType = constants.LED_STRIP
            if (self.led_type == constants.LED_STRIP_SK6812):
                ledType = ws.SK6812W_STRIP
            elif (self.led_type == constants.LED_STRIP_WS2811):
                ledType = ws.WS2811_STRIP_RGB
            elif (self.led_type == constants.LED_STRIP_WS2812B):
                ledType = ws.WS2811_STRIP_RGB

            self.pixels = PixelStrip(self.led_count, constants.LED_PIN,
                                     constants.LED_FREQ_HZ, constants.LED_DMA,
                                     constants.LED_INVERT, self.brightness,
                                     constants.LED_CHANNEL, ledType)
            self.pixels.begin()

    def pixel_off(self, args):
        self.__cancel_task()
        LedUtil.clear(self.pixels)
        self.pixels.show()

    def __execute_task(self, task, args):
        self.__cancel_task()
        self.onGoingTask = threading.Thread(target=task, args=args)
        self.onGoingTask.start()

    def __cancel_task(self):
        if (self.onGoingTask != None):
            self.cancelTask = True
            self.onGoingTask.join()
            self.cancelTask = False
Ejemplo n.º 19
0
        pixelpos -= LED_COUNT

    if (pixelpos < 0):
        pixelpos += LED_COUNT

    if (change > 0):
        strip.setPixelColor(int(pixelpos), Color(255, 0, 0))
    elif (change < 0):
        strip.setPixelColor(int(pixelpos), Color(0, 0, 255))

    return


GPIO.add_event_detect(input_a, GPIO.BOTH, callback=update)
GPIO.add_event_detect(input_b, GPIO.BOTH, callback=update)

# Main Program starts here: polling loop
while True:
    time.sleep(0.04)
    for i in range(0, LED_COUNT):
        r = (strip.getPixelColor(i) >> 16) & 0xff
        g = (strip.getPixelColor(i) >> 8) & 0xff
        b = (strip.getPixelColor(i) >> 0) & 0xff
        r = int(r * 0.8)
        g = int(g * 0.8)
        b = int(b * 0.8)
        strip.setPixelColor(i, Color(r, g, b))
    strip.show()

GPIO.cleanup()
Ejemplo n.º 20
0
class RGBMatrix:

    def __init__(self):
        # LED strip configuration:
        LED_COUNT = 64        # Number of LED pixels.
        LED_PIN = 12          # GPIO pin connected to the pixels (18 uses $
        LED_FREQ_HZ = 800000  # LED signal frequency in hertz (usually 800$
        LED_DMA = 10          # DMA channel to use for generating signal ($
        LED_BRIGHTNESS = 10   # Set to 0 for darkest and 255 for brightest
        LED_INVERT = False    # True to invert the signal (when using NPN $
        LED_CHANNEL = 0       # set to '1' for GPIOs 13, 19, 41, 45 or 53

        # TODO: root
        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()

        #  0  1  2  3  4  5  6  7
        #  8  9 10 11 12 13 14 15
        # 16 17 18 19 20 21 22 23
        # 24 25 26 27 28 29 30 31
        # 32 33 34 35 36 37 38 39
        # 40 41 42 43 44 45 46 47
        # 48 49 50 51 52 53 54 55
        # 56 57 58 59 60 61 62 63
        self.numbers = [
            [0, 1, 2, 3, 4, 5, 6, 7, 15, 23, 31, 39, 47, 55, 63, 62, 61, 60, 59, 58, 57, 56, 48, 40, 32, 24, 16, 8], # 0
            [3, 11, 19, 27, 35, 43, 51, 59], # 1
            [9, 2, 3, 4, 13, 21, 28, 28, 34, 41, 49, 57, 58, 59, 60, 61],     # 2
            [2, 3, 4, 13, 21, 28, 27, 26, 25, 37, 45, 53, 60, 59, 58, 57],    # 3
            [1, 9, 17, 25, 33, 41, 42, 43, 44, 45, 46, 47, 28, 36, 52, 60],   # 4
            [1, 9, 17, 25, 26, 27, 28, 29, 38, 46, 54, 61, 60, 59, 58, 57, 2, 3, 4, 5], # 5
            [6, 5, 4, 3, 2, 1, 9, 17, 25, 33, 41, 49, 57, 58, 59, 60, 61, 62, 54, 46, 38, 37, 36, 35, 34], # 6
            [1, 2, 3, 4, 5, 6, 7, 15, 22, 29, 36, 44, 52, 60],                # 7
            [4, 3, 2, 9, 18, 27, 36, 45, 53, 60, 59, 58, 49, 41, 34, 20, 13], # 8
            [7, 6, 5, 4, 3, 2, 1, 9, 17, 25, 33, 34, 35, 36, 37, 38, 39, 31, 23, 15, 47, 55, 63, 62, 61, 60, 59, 58, 57], # 9
            [16, 17, 18, 19, 20, 21, 22, 23, 40, 41, 42, 43, 44, 45, 46, 47, 2, 10, 26, 34, 50, 58, 5, 13, 29, 37, 53, 61], # 10 #
            [17, 18, 19, 20, 21, 22, 49, 50, 51, 52, 53, 54], # 11 =
            [28], # 12 -
            [26, 27, 28, 19, 35], # 13 +
            [7, 56, 14, 49, 21, 42, 28, 35], # 14 /
            [63, 54, 45, 36, 27, 35, 42, 49, 56, 0, 9, 18, 28, 21, 14, 7], # 15 X
        ]
        # or # color code
        #[0,  0,  0,  0,  0,  0,  0, 0,
        # 0,200,  0,  0, 70,  0,  0, 0,
        # 0,  0,  0,  0, 60,  0,  0, 0,
        # 0,  0,  0,  0, 50,  0,  0, 0,
        # 0, 10, 20, 30, 40, 30, 20, 0,
        # 0,  0,  0, 80,  0,  0,  0, 0,
        # 0,  0,  0, 90,  0,  0,  0, 0,
        # 0,  0,  0,100,  0,  0,  0, 0]

    def colorWipe(self, color, wait_ms=50):
        """Wipe color across display a pixel at a time."""
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(i, color)
            self.strip.show()
            time.sleep(wait_ms / 1000.0)

    def clear(self, r=0, g=0, b=0):
        self.colorWipe(Color(r, g, b), 5)

    def fill(self, col):
        self.colorWipe(col, 10)

    def rand(self):
        l = list(range(self.strip.numPixels()))
        random.shuffle(l)
        for i in l:
            self.strip.setPixelColor(i, Color(random.randint(10, 250), random.randint(10, 250), random.randint(10, 250)))
            self.strip.show()
            time.sleep(0.01)

    def dot(self, num, col):
        self.strip.setPixelColor(int(num), col)
        self.strip.show()

    def show_template(self, num, col):
        self.clear()
        for cell in self.numbers[int(num)]:
            self.strip.setPixelColor(cell, col)
        self.strip.show()
Ejemplo n.º 21
0
class LedRingAnimations:
    """
    Object which implements control method for the Led ring
    """
    def __init__(self):

        # - Parameters
        self.__is_simulation = rospy.get_param("~simulation_mode")

        # LED self.strip configuration:
        self.LED_COUNT = rospy.get_param('~led_count')  # Number of LED pixels.
        self.LED_PIN = rospy.get_param(
            '~led_pin')  # GPIO pin connected to the pixels (must support PWM!)
        self.LED_FREQ_HZ = rospy.get_param(
            '~led_freq_hs')  # LED signal frequency in hertz (usually 800khz)
        self.LED_DMA = rospy.get_param(
            '~led_dma')  # DMA channel to use for generating signal (try 10)
        self.LED_BRIGHTNESS = rospy.get_param(
            '~led_brightness')  # Set to 0 for darkest and 255 for brightest
        self.LED_INVERT = rospy.get_param(
            '~led_invert'
        )  # True to invert the signal (when using NPN transistor level shift)
        self.LED_CHANNEL = rospy.get_param('~led_channel')
        self.__led_offset = rospy.get_param("~led_offset")

        if not self.__is_simulation:
            self.LED_STRIP = ws.WS2811_STRIP_GRB

        # default param for led ring control methods
        self.default_flashing_period = rospy.get_param(
            '~default_flashing_period')
        self.default_alternate_period = rospy.get_param(
            '~default_alternate_period')
        self.default_chase_period = rospy.get_param('~default_chase_period')
        self.default_colorwipe_period = rospy.get_param(
            '~default_colorwipe_period')
        self.default_rainbow_period = rospy.get_param(
            '~default_rainbow_period')
        self.default_rainbowcycle_period = rospy.get_param(
            '~default_rainbowcycle_period')
        self.default_rainbowchase_period = rospy.get_param(
            '~default_rainbowchase_period')
        self.default_goup_period = rospy.get_param('~default_goup_period')
        self.default_goupanddown_period = rospy.get_param(
            '~default_goupanddown_period')
        self.default_breath_period = rospy.get_param('~default_breath_period')
        self.default_snake_period = rospy.get_param('~default_snake_period')

        self.__stop_func = False
        self.__animation_lock = Lock()

        self._observers = []

        self.current_animation_color = BLACK
        self.current_animation = LedRingAnimation.NONE
        self.set_current_anim_and_color(
            self.current_animation,
            self.current_animation_color,
        )

        if not self.__is_simulation:
            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()

        if self.__is_simulation:
            self.led_count = self.LED_COUNT
        else:
            self.led_count = self.strip.numPixels()

        self.off_color = GREY if self.__is_simulation else BLACK

        # for real mode
        # list used to store the current state of the real led ring, as a list of ColorRGBA objects
        self.current_real_led_ring_state = []

        self.led_ring_makers = LedRingSimulation(self.led_count)

        self.blackout()

    def __del__(self):
        self.set_and_show_leds(self.off_color)
        if not self.__is_simulation:
            del self.strip

    def stop_animation(self):
        """
        Stop iteration (and endless iteration) for functions that perform continous action like alternate_color, and
        wait until the previous function is finished.
        Used when launched in robot status display mode. Indeed, when used by the user,
        the previous function is stopped before, in the start thread function
        """
        if self.is_animation_running():
            self.__stop_func = True
            with self.__animation_lock:  # wait the end of the running animation
                self.blackout()

    def init_animation(self):
        self.__stop_func = False

    def is_animation_running(self):
        return self.__animation_lock.locked()

    def was_function_interrupted(self):
        return self.__stop_func  # if true, function was interrupted

    def __play_cycle_animation(self, color_cycle, period, iterations,
                               animation_function):
        # start playing animation :
        loop_period = period * 1.0 / len(color_cycle)
        next_loop_time = rospy.Time.now()

        count = 1 if not iterations else iterations
        while count > 0:
            for cycle_index in range(len(color_cycle)):
                if self.__stop_func:
                    break

                animation_function(color_cycle, cycle_index)
                next_loop_time += rospy.Duration(loop_period)
                self.__sleep_animation(next_loop_time)

            if self.__stop_func:
                break

            if iterations:
                count -= 1

        self.blackout()

    def none(self):
        """
        Turn off leds, in simu and in real, with the "solid" method
        """
        self.solid(self.off_color)

    def solid(self, color_rgba):
        """
        Sets all Leds to a color at once
        """
        self.init_animation()
        with self.__animation_lock:
            self.set_and_show_leds(color_rgba)

            mode = LedRingAnimation.NONE if color_rgba == self.off_color else LedRingAnimation.SOLID
            self.set_current_anim_and_color(mode, color_rgba)

    def custom(self, color_rgba):
        """
        Sets all Leds to a color at once
        """
        self.init_animation()
        with self.__animation_lock:
            colors = color_rgba[:self.led_count] if len(
                color_rgba) > self.led_count else color_rgba + (
                    len(color_rgba) - self.led_count) * [BLACK]

            for led_id, led_color in enumerate(colors):
                # set color led by led
                self.set_led(led_id, led_color)
            self.show_leds()  # display all leds

            self.set_current_anim_and_color(LedRingAnimation.CUSTOM)

    def set_led_color(self, led_id, color_rgba):
        self.init_animation()
        with self.__animation_lock:
            self.set_led(led_id, color_rgba)
        self.show_leds()
        self.set_current_anim_and_color(LedRingAnimation.CUSTOM)

    def flashing(self, color_rgba, period=None, iterations=0):
        """
        Flash a color according to a frequency
        """
        def animation_function(anim_color_cycle, anim_cycle_index):
            self.set_and_show_leds(anim_color_cycle[anim_cycle_index])

        self.init_animation()

        # set default frequency
        if not period:
            period = self.default_flashing_period

        # configure the animation
        color_cycle = [color_rgba, self.off_color]

        # start the animation
        with self.__animation_lock:
            self.set_current_anim_and_color(LedRingAnimation.FLASHING,
                                            color_rgba)
            self.__play_cycle_animation(color_cycle, period, iterations,
                                        animation_function)

    def alternate(self, color_list_rgba, period=None, iterations=0):
        """
        The different colors are alternated one after the other.
        If iterations is 0, do it indefinitely
        """
        def animation_function(anim_color_cycle, anim_cycle_index):
            self.set_current_anim_and_color(LedRingAnimation.ALTERNATE,
                                            anim_color_cycle[anim_cycle_index])
            self.set_and_show_leds(anim_color_cycle[anim_cycle_index])

        self.init_animation()

        # configure the animation
        if not period:
            period = self.default_alternate_period
        color_cycle = color_list_rgba[:]

        # start the animation
        with self.__animation_lock:
            self.__play_cycle_animation(color_cycle, period, iterations,
                                        animation_function)

    def chase(self, color_rgba, period=None, iterations=0):
        """
        Movie theater light style chaser animation.
        If iterations is 0, do it indefinitely
        """
        def animation_function(anim_color_cycle, anim_cycle_index):
            for led_id in range(self.led_count):
                # set color led by led
                self.set_led(
                    led_id, anim_color_cycle[led_id % len(anim_color_cycle) -
                                             anim_cycle_index])
            self.show_leds()  # display all leds

        self.init_animation()
        # configure the animation
        if not period:
            period = self.default_chase_period
        color_cycle = [self.off_color, self.off_color, color_rgba]

        # start the animation
        with self.__animation_lock:
            self.set_and_show_leds(self.off_color)
            self.set_current_anim_and_color(LedRingAnimation.CHASE, color_rgba)
            self.__play_cycle_animation(color_cycle, period, iterations,
                                        animation_function)

    def color_wipe(self, color_rgba, duration=None):
        """
        Wipe color across, light a Led at a time.
        Similar to goUp, but Leds are not turned off at the end.
        """
        self.init_animation()

        if not duration:
            duration = self.default_colorwipe_period

        with self.__animation_lock:
            self.set_current_anim_and_color(LedRingAnimation.COLOR_WIPE,
                                            color_rgba)
            self.__wipe_animation(color_rgba, duration)

            if self.__stop_func:
                self.blackout()  # turn off leds

    def __wipe_animation(self, color_rgba, duration):
        next_loop = rospy.Time.now()
        period = rospy.Duration(duration * 1.0 / self.led_count)

        for led_id in range(self.led_count):
            if self.__stop_func:
                break
            self.set_led((led_id + self.__led_offset) % self.led_count,
                         color_rgba)
            self.show_leds()

            next_loop += period
            self.__sleep_animation(next_loop)

    def breath_animation(self, color_rgba, duration):
        next_loop = rospy.Time.now()

        gamma = 0.2  # affects the width of peak (more or less darkness)
        beta = 0.5  # shifts the gaussian to be symmetric

        nb_steps = 255
        anim_period = rospy.Duration(duration * 1.0 / nb_steps)

        self.current_animation_color = color_rgba
        for counter in range(nb_steps):
            if self.__stop_func:
                break

            # value = 255 * math.sin(2 * math.pi * (counter * 1.0 / smoothness_pts))
            factor = math.exp(-(pow(
                ((counter * 1.0 / nb_steps) - beta) / gamma, 2.0)) / 2.0)

            # self.set_brightness(value)
            self.set_and_show_leds(
                ColorRGBA(self.current_animation_color.r * factor,
                          self.current_animation_color.g * factor,
                          self.current_animation_color.b * factor, 0))

            next_loop += anim_period
            rospy.sleep(next_loop - rospy.Time.now())

    def breath(self, color_rgba, period=None, iterations=0):
        """
        Leds turn on like a loading circle, and are all turned off at the same time
        If iterations is 0, do it indefinitely
        """
        self.init_animation()
        if period == 0 or period is None:
            period = self.default_breath_period

        # start playing animation :
        with self.__animation_lock:
            self.set_current_anim_and_color(LedRingAnimation.BREATH,
                                            color_rgba)
            if not iterations:
                while not self.__stop_func:
                    self.breath_animation(color_rgba, period)
            else:
                for _i in range(iterations):
                    if self.__stop_func:
                        break
                    self.breath_animation(color_rgba, period)

            self.blackout()

    def snake(self, color_rgba, period=None, iterations=0):
        def animation_function(anim_color_cycle, anim_cycle_index):
            for led_id in range(self.led_count):
                # set color led by led
                self.set_led(
                    led_id, anim_color_cycle[(led_id + anim_cycle_index) %
                                             len(anim_color_cycle)])
            self.show_leds()  # display all leds

        self.init_animation()
        # configure the animation
        if not period:
            period = self.default_snake_period

        attenuated_color = ColorRGBA(color_rgba.r * 0.5, color_rgba.g * 0.5,
                                     color_rgba.b * 0.5, 0)
        snake_length = 10
        snake_pattern = [
            attenuated_color
        ] + (snake_length - 2) * [color_rgba] + [
            attenuated_color
        ] + (self.LED_COUNT - snake_length) * [self.off_color]

        # start the animation
        with self.__animation_lock:
            self.set_and_show_leds(self.off_color)
            self.set_current_anim_and_color(LedRingAnimation.SNAKE, color_rgba)
            self.__play_cycle_animation(snake_pattern, period, iterations,
                                        animation_function)

    def go_up(self, color_rgba, period=None, iterations=0):
        """
        Leds turn on like a loading circle, and are all turned off at the same time
        If iterations is 0, do it indefinitely
        """
        def animation(duration):
            end_time = rospy.Time.now() + rospy.Duration(duration)

            self.__wipe_animation(
                color_rgba, duration * self.led_count / (self.led_count + 1))
            self.set_and_show_leds(self.off_color)
            rospy.sleep(end_time - rospy.Time.now())

        self.init_animation()
        if period == 0 or period is None:
            period = self.default_goup_period

        # start playing animation :
        with self.__animation_lock:
            self.set_current_anim_and_color(LedRingAnimation.GO_UP, color_rgba)
            if not iterations:
                while not self.__stop_func:
                    animation(period)
            else:
                for _ in range(iterations):
                    if self.__stop_func:
                        break
                    animation(period)

            self.blackout()

    def go_up_and_down(self, color_rgba, period=None, iterations=0):
        """
        Leds turn on like a loading circle, and turn off the same way
        If iterations is 0, do it indefinitely
        """
        def animation(duration):
            self.__wipe_animation(color_rgba, duration / 2.0)
            self.__wipe_animation(self.off_color, duration / 2.0)

        self.init_animation()
        if period == 0 or period is None:
            period = self.default_goupanddown_period

        with self.__animation_lock:
            self.set_current_anim_and_color(LedRingAnimation.GO_UP_AND_DOWN,
                                            color_rgba)

            # start playing animation :
            if not iterations:
                while not self.__stop_func:
                    animation(period)
            else:
                for _ in range(iterations):
                    if self.__stop_func:
                        break
                    animation(period)

            self.blackout()

    def __rainbow_animation(self, duration, animation_function):
        next_loop = rospy.Time.now()

        anim_period = rospy.Duration(duration / 256.0)
        for color_counter in range(256):
            if self.__stop_func:
                break

            animation_function(color_counter)

            next_loop += anim_period
            rospy.sleep(next_loop - rospy.Time.now())

    def rainbow(self, period=None, iterations=0):
        """
        Draw rainbow that fades across all Leds at once
        If iterations is 0, do it indefinitely
        """
        def animation(color_counter):
            # for led_id in range(self.led_count):
            #   self.set_led(led_id, wheel_rgba((led_id + color_counter) & 255))
            # self.show_leds()
            self.set_and_show_leds(wheel_rgba(color_counter & 255))

        self.init_animation()
        # configure the animation
        if not period:
            period = self.default_rainbow_period

        with self.__animation_lock:
            # no color info in led_ring_status topic, so we just notify that the animation changed
            self.set_current_anim_and_color(LedRingAnimation.RAINBOW)

            # start playing animation :

            if not iterations:
                while not self.__stop_func:
                    self.__rainbow_animation(period, animation)
            else:
                for _ in range(iterations):
                    if self.__stop_func:
                        break
                    self.__rainbow_animation(period, animation)

            self.blackout()  # turn off leds after all iterations

    def rainbow_cycle(self, period=None, iterations=0):
        """
        Draw rainbow that uniformly distributes itself across all Leds
        If iterations is 0, do it indefinitely
        """
        def animation(color_counter):
            for led_id in range(self.led_count):
                self.set_led(
                    led_id,
                    wheel_rgba(
                        int((led_id * 256.0 // self.led_count + color_counter))
                        & 255))
            self.show_leds()

        self.init_animation()
        if not period:
            period = self.default_rainbowcycle_period

        with self.__animation_lock:
            self.set_current_anim_and_color(LedRingAnimation.RAINBOW_CYLE)

            # start playing animation :
            if not iterations:
                while not self.__stop_func:
                    self.__rainbow_animation(period, animation)
            else:
                for _ in range(iterations):
                    if self.__stop_func:
                        break
                    self.__rainbow_animation(period, animation)

            self.blackout()  # turn off leds after all iterations

    def rainbow_chase(self, period=None, iterations=0):
        """
        Rainbow chase animation
        If iterations is 0, do it indefinitely
        """
        def animation(color_counter):
            for led_id in range(self.led_count):
                offset = color_counter % 3

                if (led_id + offset) % 3 == 0:
                    self.set_led(led_id,
                                 wheel_rgba((led_id + color_counter) & 255))
                else:
                    self.set_led(led_id, self.off_color)  # don't show
            self.show_leds()

        self.init_animation()
        if not period:
            period = self.default_rainbowchase_period

        with self.__animation_lock:
            self.set_current_anim_and_color(LedRingAnimation.RAINBOW_CHASE)
            self.set_and_show_leds(self.off_color)

            # start playing animation :
            if not iterations:
                while not self.__stop_func:
                    self.__rainbow_animation(period, animation)
            else:
                for _ in range(iterations):
                    if self.__stop_func:
                        break
                    self.__rainbow_animation(period, animation)

            self.blackout()  # turn off leds after all iterations

    def blackout(self):
        """
        Black out every led, without stopping previous function
        """
        self.set_and_show_leds(self.off_color)
        self.set_current_anim_and_color(LedRingAnimation.NONE, BLACK)

    def fade(self, color_rgba, duration=3.5, steps=100):
        current_color = self.current_animation_color
        step_r = (color_rgba.r - current_color.r) / float(steps)
        step_g = (color_rgba.g - current_color.g) / float(steps)
        step_b = (color_rgba.b - current_color.b) / float(steps)

        sleep_duration = duration / float(steps)
        for _ in range(steps):
            self.current_animation_color = ColorRGBA(
                self.current_animation_color.r + step_r,
                self.current_animation_color.g + step_g,
                self.current_animation_color.b + step_b, 0)
            rospy.sleep(sleep_duration)

    # - Real Led ring related method

    def get_state_list_from_pixel_strip(self):
        """
        Return a list of size self.led_count, containing the current rgb color [r, g, b] of each Led in the
        real led ring
        """
        real_leds_state = []
        if not self.__is_simulation:
            for i in range(self.led_count):
                # read back the state from the library memory buffer
                # (can't read directly Led state, they are Write-only)
                color_i = self.strip.getPixelColorRGB(i)
                real_leds_state.append([color_i.r, color_i.g, color_i.b])
        return real_leds_state

    # - Generic methods usable for simulation and real robot

    def set_led(self, index, color_rgba):
        """
        Set the color of a pixel, in simu or in real
        """
        if not self.__is_simulation:
            color = get_24bits_color_from_msg(color_rgba)
            self.strip.setPixelColor(index, color)
        self.led_ring_makers.set_one_led_marker(index, color_rgba)

    def show_leds(self):
        """
        Display all Led's values previously set, in simu or in real
        """
        if not self.__is_simulation:
            self.strip.show()

            # update value of current led state
            current_rgb_array_led_state = self.get_state_list_from_pixel_strip(
            )
            current_color_rgba_led_state = []
            # transform a list like [[r, g, b], [r, g, b], ...] to a list like [ColorRGBA, ColorRGBA, ...]
            for elem in current_rgb_array_led_state:
                current_color_rgba_led_state.append(
                    get_rgba_color_from_list(elem))
            self.set_current_real_leds_state(current_color_rgba_led_state)
        self.led_ring_makers.show_led_ring_markers()

    def set_and_show_leds(self, color, range_=None, index_delta=0):
        """
        Iterate over all leds, set them to the chosen color and show them all at once.
        "range_" must be filled only if we want to iterate over a part of the led ring.
        "index_delta" is used by "chase" methods only.
        """

        if range_ is None:
            range_ = self.led_count
            for i in range(range_):
                self.set_led(i + index_delta, color)
            self.show_leds()

        elif isinstance(range_, list) and len(range_) == 3:
            for i in range(range_[0], range_[1], range_[2]):
                self.set_led(i + index_delta, color)
            self.show_leds()

    def set_brightness(self, brightness):
        if not self.__is_simulation:
            self.strip.setBrightness(brightness)

    def __sleep_animation(self, until_time):
        while (until_time - rospy.Time.now()).to_sec() > 0.1:
            rospy.sleep(0.1)
            if self.__stop_func:
                break
        else:
            rospy.sleep(until_time - rospy.Time.now())

    # Observable related methods
    def set_current_anim_and_color(self, animation, color=None):
        self.current_animation_color = color if color is not None else BLACK
        self.current_animation = animation
        self.notify_observers()

    def set_current_real_leds_state(self, rgb_list):
        self.current_real_led_ring_state = rgb_list

    def notify_observers(self):
        """
        trigger a function in the observer (led ring node) class
        """
        for obs in self._observers:
            obs.notify_current_anim_and_color(self)

    def register_observer(self, observer):
        """
        Used to add the led ring node as an observer of this class
        """
        self._observers.append(observer)
Ejemplo n.º 22
0
class LEDStrip(object):
    """
    An object wrapper for the LED strip.
    """

    def __init__(self, n_led, led_pin):
        """
        Initialize the object.

        Args
        ----
        n_led: int
            Number of LEDs on the strip.
        led_pin: int
            GPIO bin the data line is connected to.
        """

        # Create the led strip object.
        if led_pin in [12, 18]:
            channel = 0
        elif led_pin in [13, 19]:
            channel = 1
        else:
            raise ValueError(('GPIO pin {} can not be used for the LED '
                'strip.').format(led_pin))
        self._strip = PixelStrip(n_led, led_pin, channel=channel)
        self._strip.begin()

    @property
    def n_led(self):
        """
        Return the number of LEDs on the strip.
        """
        return self._strip.numPixels()

    def flush(self, colors):
        """
        Display the colors contained in data on the strip.

        Args
        ----
        colors: Color, [Color]
            If a single color is given, the whole strip is colored with that
            color. If a list is given, colors in the list are set.
        """

        if isinstance(colors, int):
            for i_led in range(self.n_led):
                self._strip.setPixelColor(i_led, colors)
        else:
            for i_led, color in enumerate(colors):
                self._strip.setPixelColor(i_led, color)
        self._strip.show()

    def clear(self):
        """
        Deactivate all LEDs on the strip.
        """

        self.flush(Color(0, 0, 0))
        self._strip.show()
Ejemplo n.º 23
0
class neoled:

    # LED strip configuration:
    LED_COUNT = 16  # Number of LED pixels.
    LED_PIN = 10  # 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.SK6812_STRIP_GRBW

    def __init__(self):
        # Create NeoPixel object with appropriate configuration.
        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)
        # Intialize the library (must be called once before other functions).
        self.strip.begin()
        self.colorFill(Color(0, 0, 0, 0))

    # Define functions which animate LEDs in various ways.
    def colorFill(self, color):
        """Fill strip with color at once."""
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(i, color)
        self.strip.show()

    def colorWipe(self, color, wait_ms=10):
        """Wipe color across display a pixel at a time."""
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(i, color)
            self.strip.show()
            time.sleep(wait_ms / 1000.0)

    def colorBlink(self, color, blink_ms=20, nblinks=1):
        for i in range(nblinks):
            self.colorFill(color)
            time.sleep(blink_ms / 1000.0)
            self.colorFill(Color(0, 0, 0, 0))
            if i < (nblinks - 1):
                time.sleep(blink_ms / 1000.0)

    def colorBlinkPos(self, color, blink_ms=30, nblinks=1, pos=0):
        for i in range(nblinks):
            for i in range(self.strip.numPixels()):
                if ((i + pos) % 7 == 0):
                    self.strip.setPixelColor(i, color)
                else:
                    self.strip.setPixelColor(i, Color(0, 0, 0, 0))
            self.strip.show()
            time.sleep(blink_ms / 1000.0)
            self.colorFill(Color(0, 0, 0, 0))
            if i < (nblinks - 1):
                time.sleep(blink_ms / 1000.0)

    def multColor(self, color, multiplier):
        white = (color >> 24) & 0xFF
        red = (color >> 16) & 0xFF
        green = (color >> 8) & 0xFF
        blue = color & 0xFF
        return Color(int(red * multiplier), int(green * multiplier),
                     int(blue * multiplier), int(white * multiplier))

    def dualbulb(self, color, pos):
        dualbulb_pattern = {
            0: 0.1,
            1: 0.2,
            2: 0.5,
            3: 1,
            4: 0.5,
            5: 0.2,
            6: 0.5,
            7: 1,
            8: 0.5,
            9: 0.2,
            10: 0.1,
            11: 0.2,
            12: 0.5,
            13: 1,
            14: 0.5,
            15: 0.2,
        }
        return self.multColor(color, dualbulb_pattern[pos % 16])

    def nightlight(self, color):
        wait_ms = 25
        # Ramp UP 0-0.5
        s = 0
        for j in range(10):
            s += 0.05
            for i in range(self.strip.numPixels()):
                self.strip.setPixelColor(
                    i, self.multColor(self.dualbulb(color, i), s))
            self.strip.show()
            time.sleep(wait_ms / 1000.0)
        for c in range(5):
            # Ramp UP 0.5-1
            s = 0.5
            for j in range(10):
                s += 0.05
                for i in range(self.strip.numPixels()):
                    self.strip.setPixelColor(
                        i, self.multColor(self.dualbulb(color, i + c), s))
                self.strip.show()
                time.sleep(wait_ms / 1000.0)
            # Ramp DOWN 1-05
            for j in range(10):
                s -= 0.05
                for i in range(self.strip.numPixels()):
                    self.strip.setPixelColor(
                        i, self.multColor(self.dualbulb(color, i + c), s))
                self.strip.show()
                time.sleep(wait_ms / 1000.0)
        # Ramp DOWN 0.5-0
        for j in range(10):
            s -= 0.05
            for i in range(self.strip.numPixels()):
                self.strip.setPixelColor(
                    i, self.multColor(self.dualbulb(color, i), s))
            self.strip.show()
            time.sleep(wait_ms / 1000.0)
        self.colorFill(Color(0, 0, 0))

    def wheel(self, pos):
        """Generate rainbow colors across 0-255 positions."""
        if pos < 85:
            return Color(pos * 3, 255 - pos * 3, 0)
        elif pos < 170:
            pos -= 85
            return Color(255 - pos * 3, 0, pos * 3)
        else:
            pos -= 170
            return Color(0, pos * 3, 255 - pos * 3)

    def rainbow(self, wait_ms=20, iterations=1):
        """Draw rainbow that fades across all pixels at once."""
        for j in range(256 * iterations):
            for i in range(self.strip.numPixels()):
                self.strip.setPixelColor(i, wheel((i + j) & 255))
            self.strip.show()
            time.sleep(wait_ms / 1000.0)

    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(((i * 256 // self.strip.numPixels()) + j) & 255))
            self.strip.show()
            time.sleep(wait_ms / 1000.0)
Ejemplo n.º 24
0
class Led(Thread):

    # LED strip configuration:
    LED_COUNT = 95  # 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 = 170  # 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
    FRAMERATE = 50

    def __init__(self):
        # Create NeoPixel object with appropriate configuration.
        self.strip = PixelStrip(self.LED_COUNT, \
                                self.LED_PIN, \
                                self.LED_FREQ_HZ, \
                                self.LED_DMA, \
                                self.LED_INVERT, \
                                self.LED_BRIGHTNESS//2, \
                                self.LED_CHANNEL)
        # Intialize the library (must be called once before other functions).
        self.strip.begin()

        # Variables that store what the LEDs will do

        self.loop = False  # whether the current sequence of frames should be
        # repeated after completion

        self.colorSeqs = {}  # a dictionary storing color sequences
        # KEY: the key is arbitrary, to distinguish different color sequences
        #      - It is up to the implementation to determine the key
        # VAL: a list of colors, stored as integers, that form the sequence
        #      - All values in colorSeqs must have the same length

        self.seqLen = 0  # the length of color sequences in colorSeqs

        self.mapping = []  # a list containing integers
        # these integers correspond to indices in colorSeqs
        # length of mapping = number of LEDs in the LightBox

        self.currInd = 0  # an integer marking where in the color sequences the LEDs are

        self.targetBrightness = self.strip.getBrightness(
        )  # value storing brightness to be attained
        # during gradual fade towards it

        # Initialize these variables for the first time (LEDs off)
        self.loop = False
        self.colorSeqs[0] = [0x000000]
        self.seqLen = 1
        self.mapping = [0] * self.strip.numPixels()
        self.currInd = 0
        # These settings will cause the LED's to switch to #000000 (off) once

        # Start thread that will handle LED changes in the background
        Thread.__init__(self)
        self.daemon = True

        print("Led Strip Initialized")

    # Continuous loop that handles LED changes registered in mapping and colorSeqs
    def run(self):
        while True:
            refreshStrip = True
            time.sleep(1.0 / self.FRAMERATE)

            if self.currInd == self.seqLen:  #reached end of sequence
                if self.loop:
                    self.currInd = 0  #loop to beginning of sequence
                else:
                    refreshStrip = False

            if refreshStrip:
                try:
                    for i in range(self.strip.numPixels()):
                        self.strip.setPixelColor(
                            i, self.colorSeqs[self.mapping[i]][self.currInd])
                except KeyError:
                    print("Error: invalid key %d" % self.mapping[i])
                    continue
                self.currInd += 1

            if self.strip.getBrightness() != self.targetBrightness:
                self.strip.setBrightness( max( min(
                        self.strip.getBrightness() + (self.FRAMERATE//25) * \
                        (1 if self.targetBrightness > self.strip.getBrightness() else -1) \
                    , 255), 0) \
                )
                if (abs(self.targetBrightness -
                        self.strip.getBrightness())) < (self.FRAMERATE // 25):
                    self.strip.setBrightness(self.targetBrightness)
                refreshStrip = True

            if refreshStrip:
                self.strip.show()

    # Color Manipulation functions...

    def solidColor(self, color):
        ''' Changes LightBox to a solid color, defined by color '''

        colorSeqs = {}
        mapping = [0] * self.strip.numPixels()

        # Iterate through each led in the strip
        for currLed in range(self.strip.numPixels()):
            # Add entry to mapping for the color sequence
            mapping[currLed] = self.strip.getPixelColor(currLed)

            # Add sequence to colorSeqs if it doesn't exist already
            if mapping[currLed] not in colorSeqs:
                colorSeqs[mapping[currLed]] = \
                    colorUtil.linear_gradient(mapping[currLed], \
                                              color, \
                                              self.FRAMERATE//4)

        self.loop = False
        self.seqLen = self.FRAMERATE // 4
        self.currInd = 0
        self.mapping = mapping
        self.colorSeqs = colorSeqs

    def clear(self):
        '''clears all leds'''
        self.solidColor(0)

    def changeBrightness(self, newBrightnessValue):
        '''sets brightness of LEDs (0-100)'''
        self.targetBrightness = int(self.LED_BRIGHTNESS *
                                    newBrightnessValue**1.5 /
                                    1000)  #1000=100^1.5

    def rainbow(self):
        '''creates a rainbow sequence that loops'''

        #generates list of colors that cycle in hue
        numFrames = self.FRAMERATE * 10  # the number is how many seconds per rainbow cycle
        rainbowColors = [
            colorUtil.HSV_to_hex(k / numFrames * 360, 1, 1)
            for k in range(0, numFrames, 1)
        ]

        colorSeqs = {}
        seqLen = len(rainbowColors)
        mapping = [0] * self.strip.numPixels()

        for led in range(self.strip.numPixels()):
            mapping[led] = led  #unique mapping for each led
            colorSeqs[led] = [0] * seqLen

        for colorPos in range(seqLen):
            for led in range(self.strip.numPixels()):
                colorSeqs[led][colorPos] = rainbowColors[(colorPos + led) %
                                                         seqLen]

        self.loop = True
        self.seqLen = seqLen
        self.currInd = 0
        self.colorSeqs = colorSeqs
        self.mapping = mapping

    def sparkle(self, seqLenSeconds=30):
        '''creates a sparkle sequence that loops'''

        numFrames = self.FRAMERATE * 1  # the number is how many seconds for average flash
        deviation = self.FRAMERATE // 2  # random deviation of the flash lengths
        satChoice = ([0.0]) + ([0.5] * 5) + (
            [1] * 50)  # weighted probability for saturation
        # prevents too many 'white' LEDs
        valChoice = ([0.2]) + ([0.5] * 5) + (
            [1] * 10)  # weighted probability for value
        # prevents too many dim LED's

        colorSeqs = {}
        seqLen = numFrames * seqLenSeconds
        mapping = [0] * self.strip.numPixels()

        for led in range(self.strip.numPixels()):
            mapping[led] = led  # unique mapping for each led
            colorSeqs[led] = [0] * seqLen

        for colorPos in range(seqLen):

            for i in range(random.randrange(
                    0, 4)):  # repeat a random number of times
                # to create variety

                led = random.randrange(0, self.strip.numPixels())
                if colorSeqs[led][colorPos] != 0:  # already a flash at that led
                    continue  # don't overwrite it
                duration = random.randint(numFrames - deviation,
                                          numFrames + deviation)
                hue = random.uniform(0, 360)
                sat = random.choice(satChoice)
                val = random.choice(valChoice)

                for k in range(duration):
                    # fill in colorSeqs for the flash, given by the piecewise function
                    # at https://www.desmos.com/calculator/lmsoc2uoif
                    colorSeqs[led][(colorPos+k)%seqLen] = colorUtil.HSV_to_hex(hue, sat, \
                        val * ( (3/duration)*k if k < duration/3 \
                        else (-3/(2*duration))*(k-duration) ) \
                    )

        self.loop = True
        self.seqLen = seqLen
        self.currInd = 0
        self.colorSeqs = colorSeqs
        self.mapping = mapping
Ejemplo n.º 25
0
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)
strip.begin()


def wheel(pos):
    """Generate rainbow colors across 0-255 positions."""
    if pos < 85:
        return Color(pos * 3, 255 - pos * 3, 0)
    elif pos < 170:
        pos -= 85
        return Color(255 - pos * 3, 0, pos * 3)
    else:
        pos -= 170
        return Color(0, pos * 3, 255 - pos * 3)


for j in range(256):
    for i in range(strip.numPixels()):
        strip.setPixelColor(
            i, wheel((int(i * 256 / strip.numPixels()) + j) & 255))
    strip.show()

print('done')
Ejemplo n.º 26
0
            frame_index += 1
        else:
            break

    print('Press Ctrl-C to quit.')

    try:
        # 再生
        print('Start playing')
        while (True):
            start = time.time()
            for i in range(len(pixel_values)):
                for k in range(LED_COUNT):
                    strip.setPixelColor(
                        k,
                        Color(int(pixel_values[i][k][0]),
                              int(pixel_values[i][k][1]),
                              int(pixel_values[i][k][2])))
                strip.show()
                #時間合わせ
                elapsed_time = time.time() - start
                if ((1 / FPS * (i + 1)) > elapsed_time):
                    time.sleep((1 / FPS) * (i + 1) - elapsed_time)
            print('---------------------------------')
            print("playing ended.\nActual time:{0}".format(elapsed_time) +
                  "[sec]")
            clear()
            time.sleep(0.5)

    except KeyboardInterrupt:
        clear()
Ejemplo n.º 27
0
def main():

    # Register the encoder to handle changing the brightness
    knob = encoder.RotaryEncoder(callback=on_turn)

    def on_exit(sig, frame):
        knob.destroy()
        set_all(leds, BLACK)
        sys.exit(0)

    signal.signal(signal.SIGINT, on_exit)
    signal.signal(signal.SIGTERM, on_exit)

    cron.set_upgrade_schedule()

    cfg = load_configuration()

    if cfg.getboolean('settings', 'papertrail', fallback=True):
        from rpi_metar import papertrail
        logger = logging.getLogger('rpi_metar')
        logger.addHandler(papertrail)

    kwargs = {
        'num': max((airport.index for airport in AIRPORTS.values())) + 1,
        'pin': 18,
        'gamma': GAMMA,
        'brightness': int(cfg.get('settings', 'brightness', fallback=128))
    }
    # Sometimes if we use LED strips from different batches, they behave differently with the gamma
    # controls and brightness levels. Therefore we need to be able to disable the gamma controls.
    if cfg.get('settings', 'disable_gamma', fallback=False):
        kwargs.pop('gamma')

    leds = PixelStrip(**kwargs)
    leds.begin()
    leds.lock = threading.Lock()
    set_all(leds, BLACK)

    for airport in AIRPORTS.values():
        leds.setPixelColor(airport.index, YELLOW)
    leds.show()

    # Kick off a thread to handle adjusting the brightness
    t = threading.Thread(name='brightness',
                         target=wait_for_knob,
                         args=(ENCODER_EVENT, leds, cfg))
    t.start()

    # A thread to fetch metar information periodically
    t = threading.Thread(name='metar_fetcher',
                         target=fetch_metars,
                         args=(METAR_QUEUE, cfg))
    t.start()

    # A thread to process metar info.
    t = threading.Thread(name='metar_processor',
                         target=process_metars,
                         args=(METAR_QUEUE, leds))
    t.start()

    # A thread to change the LEDs when airport categories change.
    t = threading.Thread(name='render_leds',
                         target=render_leds,
                         args=(LED_QUEUE, leds, cfg))
    t.start()

    # A thread for lightning
    if cfg.get('settings', 'lightning', fallback=True):
        t = threading.Thread(name='lightning',
                             target=lightning,
                             args=(leds, METAR_EVENT, cfg))
        t.start()

    # A thread for wind
    if cfg.get('settings', 'wind', fallback=True):
        t = threading.Thread(name='wind',
                             target=wind,
                             args=(leds, METAR_EVENT, cfg))
        t.start()
Ejemplo n.º 28
0
class Light:
    """
  Class that represents a LED light strip connected to a Raspberry PI through a single I/O port.
  Data going through that I/O port and power supplied externally (because it's too much for the PI
  to power them if there are too many).
  """
    def __init__(self, name: str):
        """ Constructor, initializing members with default values. """
        print("  ..creating light object: " + name)
        self._name = name  # Human name of the LED strip;
        self._ledCount = 100  # Number of individually addressable LEDs on the strip;
        self._redRGB = 1  # RGB Red color value;
        self._greenRGB = 1  # RGB Green color value;
        self._blueRGB = 1  # RGB Blue color value;
        self._ledBrightness = 255  # Set to 0 for darkest and 255 for brightest;
        self._ledFrequency = 800000  # LED signal frequency in hertz (usually 800khz);
        self._ledDmaChannel = 10  # DMA channel to use for generating signal (try 10);
        self._ledInvert = False  # True to invert the signal (when using NPN transistor level shift);
        self._ledChannel = 0
        self._stripGpioPin = 18  # RaspberryPI GPIO pin that is used to drive the LED strip;
        self._stripType = ws.SK6812_STRIP_RGBW  # The type of the LED strip (just RGB or does it also include a White LED);
        self._strip = None  # Instance of the rpi_ws281x LED strip;
        self._lightState = False  # Is the light "off" (false) or "on" (true);
        self._switches = [
        ]  # Optional list of Switch objects that are linked to this light object;
        self._debug = False  # Debug level logging;

    def __del__(self):
        """ Destructor will turn off this light. """
        print("destroying light object: " + self._name)
        self.Off()

    @property
    def name(self):
        """ Return the name of this light. """
        return self._name

    @name.setter
    def name(self, value: str):
        """ Set the name for this light. """
        self._name = value

    @property
    def ledCount(self) -> int:
        """ Return the number of individual LEDs on the light strip. """
        return self._ledCount

    @ledCount.setter
    def ledCount(self, value: int):
        """ Set the number of LEDs to use on this light strip.  You can activate fewer than available. """
        if not (value > 0):
            raise Exception("You need to have at least 1 LED on the strip!")
        self._ledCount = value

    @property
    def redRGB(self) -> int:
        """ Return the current Red RGB color value for the light strip. """
        return self._redRGB

    @redRGB.setter
    def redRGB(self, value: int):
        """ Set the red RGB color value of LEDs to use on this light strip. """
        if not ((value >= 0) and (value <= 255)):
            raise Exception("The red RGB value needs to be between 0 and 255!")
        self._redRGB = value

    @property
    def greenRGB(self) -> int:
        """ Return the current Green RGB color value for the light strip. """
        return self._greenRGB

    @greenRGB.setter
    def greenRGB(self, value: int):
        """ Set the green RGB color value of LEDs to use on this light strip. """
        if not ((value >= 0) and (value <= 255)):
            raise Exception(
                "The green RGB value needs to be between 0 and 255!")
        self._greenRGB = value

    @property
    def blueRGB(self) -> int:
        """ Return the current Blue RGB color value for the light strip. """
        return self._blueRGB

    @blueRGB.setter
    def blueRGB(self, value: int):
        """ Set the blue RGB color value of LEDs to use on this light strip. """
        if not ((value >= 0) and (value <= 255)):
            raise Exception(
                "The blue RGB value needs to be between 0 and 255!")
        self._blueRGB = value

#  @property
#  def ledColor(self) -> str:
#    """ Return the RGB color value of the LEDs. """
#    return self._ledColor
#
#  @ledColor.setter
#  def ledColor(self, value: str):
#    """ Set the RGB color value of the LEDs. """
#    self._ledColor=value

    @property
    def ledBrightness(self) -> int:
        """ Return the brightness that the LED have been configured with (0 to 255). """
        return self._ledBrightness

    @ledBrightness.setter
    def ledBrightness(self, value: int):
        """ Set the brightness of the LEDs (0 to 255). """
        if not ((value > 0) and (value <= 255)):
            raise Exception("Brightness needs to be between 1 and 255!")
        self._ledBrightness = value

    @property
    def stripGpioPin(self) -> int:
        """ Return the Raspberry PI GPIO pin the LED strip is connected to (data). """
        return self._stripGpioPin

    @stripGpioPin.setter
    def stripGpioPin(self, value: int):
        """ Set the Raspberry PI GPIO pin the LED strip is connected to (data). """
        # The number of valid GPIO ports is limited and specific.
        # A good validator should check the port based on RPi model and throw an exception if the
        # selected port does not work to drive a LED strip like these.
        # I've decided to have a very rough validator here that enforces a port between 2 and 26.
        # I know this is not a great validator and I should probably make it more specific at some point.
        if not ((value >= 2) and (value <= 26)):
            raise Exception("The RPi GPIO port needs to be between 2 and 26!")
        self._stripGpioPin = value

    @property
    def state(self) -> bool:
        """ Show if the light is currently on or off.  "True" means "On" and "False" means "Off". """
        return self._lightState

    @property
    def debug(self) -> bool:
        """ Return the debug-flag that is set for this light. """
        return self._debug

    @debug.setter
    def debug(self, flag: bool):
        """ Set the debug level. """
        self._debug = flag

    @property
    def switches(self) -> list:
        """ Return a list of 0 or more Switch objects that have been mapped to this light. """
        return self._switches

    def addSwitch(self, switch):
        """ Add a new Switch object that can control this light. """
        self._switches.append(switch)

    def delSwitch(self, switch):
        """ Remove a switch from this light. """
        self._switches.remove(switch)
        del switch

    def Start(self):
        """ Initialize the LED strip at the hardware level so that we can start control the individual LEDs. """
        self._strip=PixelStrip(self._ledCount, \
                    self._stripGpioPin, \
                    self._ledFrequency, \
                    self._ledDmaChannel, \
                    self._ledInvert, \
                    self._ledBrightness, \
                    self._ledChannel, \
                    self._stripType)
        # Initialize the library (must be called once before other functions):
        self._strip.begin()

    def On(self):
        """ Turn the leds on. """
        # Set the led color, full brightness:
        color = Color(self._greenRGB, self._redRGB, self._blueRGB,
                      self._ledBrightness)
        for i in range(self._strip.numPixels()):
            self._strip.setPixelColor(i, color)
        self._strip.show()
        self._lightState = True

    def Off(self):
        """ Turn the leds off. """
        color = Color(0, 0, 0, 0)
        for i in range(self._strip.numPixels()):
            self._strip.setPixelColor(i, color)
        self._strip.show()
        self._lightState = False

    def Toggle(self):
        """ Toggle the light on or off. """
        if self._lightState:
            self.Off()
        else:
            self.On()

    def Update(self):
        """ Apply the Updated LED settings if they are on. """
        if self._lightState:
            self.Off()
            self.On()
Ejemplo n.º 29
0
class LEDController:

    """ Takes care of lighting effects for Voxx

    @params: LED_COUNT: Number of LEDs to light up
             LED_PIN  : Which pin LED is connected to
             LED_FREQ_HZ: Signal frequency in Hz
             LED_DMA: DMA channel for generating the signal - defaults to 10
             LED_INVERT: Option to invert signal. Default False
             LED_BRIGHTNESS: Max brightness of LEDs - set to 10. Max 255
             LED_CHANNEL: Defaults to 0
             LED_STRIP: LED strip type. 'ws.WS2811_STRIP_RGB' to be used for Voxx
    """
    def __init__(self,LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA,LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL,LED_STRIP):
        self._strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA,LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL,LED_STRIP)
        self._strip.begin()
        self._step = 0.5
        self._start = 0

    """Sets all pixels to 'color - Color(R,G,B)' color given by RGB values from 0-255"""
    def color_wipe(self,color,wait_ms=50):
        for i in range(0,self._strip.numPixels()):
            self._strip.setPixelColor(i, color)
            time.sleep(wait_ms / 1000.0)
        self._strip.show()
            #time.sleep(wait_ms / 1000.0)

    """ Minimum brightness idle state lighting"""
    def idle_lighting(self):
        self.color_wipe(Color(50,50,50),0)

    """ Maximum brightness listening state lighting"""
    def listening_lighting(self):
        #proximity = ProximityController.get_proximity_data()
        self.color_wipe(Color(255,255,255),0)

    """ Maps 'x' in input range to output range """
    def map_range(self,x, inLow, inHigh, outLow, outHigh):
        inRange = inHigh - inLow
        outRange = outHigh - outLow
        inScale = float(x - inLow)/float(inRange)
        return outLow + (inScale * outRange)
    """
    # Alternate breathing effect if signalling does not work
    def breathing_effect(self):
        self._start = 0
        has_responded = 0
        while True:
            if tts.responding:
                duty = self.map_range(math.sin(self._start),-1,1,0,255)
                self._start += self._step
                #self.color_wipe(Color(0,0,0,int(duty)),0)
                self.color_wipe(Color(int(duty),int(duty),int(duty)),0)
                time.sleep(0.05)
                has_responded = 1

            elif has_responded:
                break
            time.sleep(0.1)
    """

    """ Breathing effect for response state lighting"""
    def breathing_effect(self):
        self._start = 0
        tts.response_available.wait()
        print("response lighting")
        while tts.responding:
        #while True:
            duty = self.map_range(math.sin(self._start),-1,1,0,200)
            self._start += self._step
            #self.color_wipe(Color(0,0,0,int(duty)),0)
            self.color_wipe(Color(int(duty),int(duty),int(duty)),0)
            time.sleep(0.2)

    """ Lights up alternate LEDs """
    def alternate_lighting(self,color,wait_ms=50):
        for i in range(0,self._strip.numPixels(),2):
            self._strip.setPixelColor(i, color)
            time.sleep(wait_ms / 1000.0)
        self._strip.show()
        time.sleep(1)

    """ Maps user distance to light intensity """
    def greeting_effect(self,distance):
        if(distance > 2500):
            brightness = 50
        else:
            brightness = self.map_range(-distance,-2500,0,50,200)
        print(str(brightness))
        #time.sleep(0.1)
        self.color_wipe(Color(int(brightness),int(brightness),int(brightness)),0)

    """ Indicates unavailability of internet """
    def blink(self):
        while(True):
            self.color_wipe(Color(50,50,50),0)
            time.sleep(1)
            self.color_wipe(Color(0,0,0),0)
            time.sleep(1)

    """ Wave effect to convey that Voxx is 'thinking' """
    def wave_effect(self,color=Color(255,255,255),wait_ms=5):
        while tts.thinking:
            for i in range(0,self._strip.numPixels(),5):
                if(tts.thinking == 0):
                    break
                self.switch_off()
                for j in range(0,10):
                    self._strip.setPixelColor(i+j, color)
                    time.sleep(wait_ms / 1000.0)
                self._strip.show()

            for i in range(self._strip.numPixels(),-1,-5):
                if(tts.thinking == 0):
                    break
                self.switch_off()
                for j in range(0,min(10,i)):
                    self._strip.setPixelColor(i-j, color)
                    time.sleep(wait_ms / 1000.0)
                self._strip.show()
            time.sleep(0.1)

    def switch_off(self):
        self.color_wipe(Color(0,0,0),0)
Ejemplo n.º 30
0
# Get length of DNA to light up
with open("dna.fasta") as file:
    sequence = file.read()
    seqlen = len(sequence)

# Main loop
strip.begin()  # Make sure to call before other functions

try:
    while True:
        with open("dna.fasta") as file:
            for i in range(seqlen - LED_COUNT):
                seqframe = file.read(LED_COUNT)
                for n in range(LED_COUNT):
                    if seqframe[n] == 'A':
                        strip.setPixelColor(
                            n, Color(A_color[0], A_color[1], A_color[2]))
                    elif seqframe[n] == 'T':
                        strip.setPixelColor(
                            n, Color(T_color[0], T_color[1], T_color[2]))
                    elif seqframe[n] == 'G':
                        strip.setPixelColor(
                            n, Color(G_color[0], G_color[1], G_color[2]))
                    elif seqframe[n] == 'C':
                        strip.setPixelColor(
                            n, Color(C_color[0], C_color[1], C_color[2]))
                strip.show()
                time.sleep(0.1)
                file.seek(i)
except KeyboardInterrupt:
    colorWipe(strip, Color(0, 0, 0), 10)