Beispiel #1
0
class StripController:
  def __init__(self):
    self.ledCount_ = 100
    self.height_ = 10
    self.neopixel_ = Adafruit_NeoPixel(
        self.ledCount_,  # LED count
        18,  # LED pin
        800000,  # LED signal frequency (Hz)
        10,  # DMA channel
        False,  # Invert signal
        100,  # Brightness (0, 255)
        0)  # LED channel
    self.neopixel_.begin()

  def set(self, index, color):
    if index >= self.ledCount_:
      raise Exception('setting out of bounds pixel', index)
    self.neopixel_.setPixelColor(index, color)

  def show(self):
    self.neopixel_.show()

  def cleanUpGrid(self):
    width = self.ledCount_ / self.height_
    return [[BLACK] * width] * self.height_
Beispiel #2
0
class PiWS281X(DriverBase):
    """
    Driver for controlling WS281X LEDs via the rpi_ws281x C-extension.
    Only supported on the Raspberry Pi 2 & 3
    """
    def __init__(self, num, gamma=gamma.NEOPIXEL, c_order=ChannelOrder.RGB, gpio=18,
                 ledFreqHz=800000, ledDma=5, ledInvert=False, **kwds):
        """
        num - Number of LED pixels.
        gpio - GPIO pin connected to the pixels (must support PWM! GPIO 13 or 18 (pins 33 or 12) on RPi 3).
        ledFreqHz - LED signal frequency in hertz (800khz or 400khz)
        ledDma - DMA channel to use for generating signal (Between 1 and 14)
        ledInvert - True to invert the signal (when using NPN transistor level shift)
        """
        super().__init__(num, c_order=c_order, gamma=gamma, **kwds)
        self.gamma = gamma
        self._strip = Adafruit_NeoPixel(num, gpio, ledFreqHz,
                                        ledDma, ledInvert, 255, 0, 0x081000)
        # Intialize the library (must be called once before other functions).
        self._strip.begin()

    def set_brightness(self, brightness):
        self._strip.setBrightness(brightness)
        return True

    def _compute_packet(self):
        self._render()
        data = self._buf
        self._packet = [tuple(data[(p * 3):(p * 3) + 3]) for p in range(len(data) // 3)]

    def _send_packet(self):
        for i, p in enumerate(self._packet):
            self._strip.setPixelColor(i, NeoColor(*p))

        self._strip.show()
Beispiel #3
0
class DriverPiWS281X(DriverBase):

    def __init__(self, num, gamma=gamma.NEOPIXEL, c_order=ChannelOrder.RGB, ledPin=18, ledFreqHz=800000, ledDma=5, ledInvert=False):
        """
        num - Number of LED pixels.
        ledPin - GPIO pin connected to the pixels (must support PWM! pin 13 or 18 on RPi 3).
        ledFreqHz - LED signal frequency in hertz (800khz or 400khz)
        ledDma - DMA channel to use for generating signal (Between 1 and 14)
        ledInvert - True to invert the signal (when using NPN transistor level shift)
        """
        super(DriverPiWS281X, self).__init__(num, c_order=c_order, gamma=gamma)
        self.gamma = gamma
        self._strip = Adafruit_NeoPixel(num, ledPin, ledFreqHz, ledDma, ledInvert, 255, 0, 0x081000)
        # Intialize the library (must be called once before other functions).
        self._strip.begin()

    # Set Brightness of the strip. A brightness of 0 is the darkest and 255 is
    # the brightest
    def setMasterBrightness(self, brightness):
        self._strip.setBrightness(brightness)

    # Push new data
    def update(self, data):
        # handle channel order and gamma correction
        self._fixData(data)
        data = self._buf

        pixels = [tuple(data[(p * 3):(p * 3) + 3])
                  for p in range(len(data) / 3)]

        for i in range(len(data) / 3):
            self._strip.setPixelColor(i, NeoColor(pixels[i][0], pixels[i][1], pixels[i][2]))

        self._strip.show()
Beispiel #4
0
class LEDStripPWM(LEDStrip):
    def __init__(self, array: TileArray):
        super().__init__(array)
        from neopixel import Adafruit_NeoPixel
        # Create NeoPixel object with appropriate configuration.
        self.strip = Adafruit_NeoPixel(array.size(), LED_PIN, LED_FREQ_HZ,
                                       LED_DMA, LED_INVERT, LED_BRIGHTNESS,
                                       LED_CHANNEL)
        # Intialize the library (must be called once before other functions).
        self.strip.begin()

    def draw(self, image: np.ndarray, delay: float = 0.001):
        from neopixel import Color
        start = time.time()
        for y in range(image.shape[0]):
            for x in range(image.shape[1]):
                idx = self.array.index(x, y)
                r = int(image[y][x][0])
                g = int(image[y][x][1])
                b = int(image[y][x][2])
                color = Color(g, r, b)
                self.strip.setPixelColor(idx, color)
        self.strip.show()
        end = time.time()
        delta = end - start
        if delay > delta:
            time.sleep(delay - delta)
Beispiel #5
0
class NeoPixelRenderer(Renderer):
    def __init__(self, led_dma=10, led_strip=ws.WS2811_STRIP_GRB):
        super(NeoPixelRenderer, self).__init__()

        self.led_dma = 10
        self.led_strip = led_strip
        self.strip = None

    def setup(self, pixel_count, world):
        super(NeoPixelRenderer, self).setup(pixel_count, world)

        self.strip = Adafruit_NeoPixel( pixel_count,
                                        LED_PIN,
                                        LED_FREQ_HZ,
                                        self.led_dma,
                                        LED_INVERT,
                                        LED_BRIGHTNESS,
                                        LED_CHANNEL,
                                        self.led_strip)
        self.strip.begin()
        self.log.debug("LED strip initialized")

        for idx in range(0, pixel_count):
            self.strip.setPixelColorRGB(idx, 0, 0, 0, 0)
        self.strip.show()
        self.log.debug("LED strip cleared")

    def render_buffer(self, pixel_buffer):
        super(NeoPixelRenderer, self).render_buffer(pixel_buffer)

        if self._is_buffer_changed(pixel_buffer):
            for idx, pixel in enumerate(pixel_buffer):
                self.strip.setPixelColorRGB(idx, int(pixel.r), int(pixel.g), int(pixel.b))  # , int(pixel.w))

            self.strip.show()
Beispiel #6
0
class NeoPixels(object):
    LED_COUNT = 256  # Number of LED pixels.
    LED_PIN = 21  # GPIO pin connected to the pixels (must support PWM!). 18=PWM, 21=PCM, 10=SPI-MOSI
    LED_FREQ_HZ = 800000  # LED signal frequency in hertz (usually 800khz)
    LED_DMA = 5  # DMA channel to use for generating signal (try 5)
    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)

    def __init__(self):
        from neopixel import Adafruit_NeoPixel as NeoPixel

        self._pixels = NeoPixel(num=self.LED_COUNT,
                                pin=self.LED_PIN,
                                freq_hz=self.LED_FREQ_HZ,
                                dma=self.LED_DMA,
                                invert=self.LED_INVERT,
                                brightness=self.LED_BRIGHTNESS)
        try:
            self._pixels.begin()
            _logger.info("Initialized NeoPixel OK")
        except RuntimeError:
            _logger.error("Failed to initialize NeoPixels")
            raise

        self.write_pixels(np.zeros((16, 16, 3)))

    def write_pixels(self, data):
        for y, row in enumerate((data * 255).astype(np.uint8)):
            for x, color in enumerate(row):
                self._pixels.setPixelColorRGB(y * 16 + x, *color)
        self._pixels.show()
Beispiel #7
0
class LEDStrip(object):
    def __init__(self, array: TileArray):
        from neopixel import Adafruit_NeoPixel
        # Create NeoPixel object with appropriate configuration.
        self.strip = Adafruit_NeoPixel(array.size(), LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS,
                                       LED_CHANNEL)
        # Intialize the library (must be called once before other functions).
        self.strip.begin()
        self.array = array

    def draw(self, image: np.ndarray, delay: float = 0.001):
        """
        Draws a matrix of color values to the dancefloor tiles. Handles the math of calculating what pixels
        correspond to which LEDs in the chain of LED strips. The input image should have a shape of
        (height, width, 3) where height is the LEDs in the vertical direction and width is the total LEDs in
        the horizontal direction.
        :param image: Matrix of colors to display on the dancefloor
        :param delay: Seconds to wait after finishing writing to the LED strips
        """
        from neopixel import Color
        start = time.time()
        for y in range(image.shape[0]):
            for x in range(image.shape[1]):
                idx = self.array.index(x, y)
                r = int(image[y][x][0])
                g = int(image[y][x][1])
                b = int(image[y][x][2])
                color = Color(g, r, b)
                self.strip.setPixelColor(idx, color)
        self.strip.show()
        end = time.time()
        delta = end - start
        if delay > delta:
            time.sleep(delay - delta)
Beispiel #8
0
class Matrix:
    def __init__(self):
        # LED strip configuration:
        self.led_count = 256  # Number of LED pixels.
        self.led_pin = 18  # GPIO pin connected to the pixels (18 uses PWM!).
        self.led_freq_hz = 800000  # LED signal frequency in hertz (usually 800khz)
        self.led_dma = 10  # DMA channel to use for generating signal (try 10)
        self.led_brightness = 15  # Set to 0 for darkest and 255 for brightest
        self.led_invert = False  # True to invert the signal (when using NPN transistor level shift)
        self.led_channel = 0  # set to '1' for GPIOs 13, 19, 41, 45 or 53

        self.matrix = Adafruit_NeoPixel(self.led_count, self.led_pin,
                                        self.led_freq_hz, self.led_dma,
                                        self.led_invert, self.led_brightness,
                                        self.led_channel)

        self.matrix.begin()
        self.frame = Frame(rows=8, cols=32)

    def color_wipe(self, color: Color = Color()):
        for x, y, pixel in self.frame.fill():
            pixel.color = color

    def display_text(self, color: Color = Color(), row_1=""):
        t = Text(row_1)
        t = t.array

        for i in range(self.frame.cols()):
            for x, y, pixel in self.frame.fill():
                if t[x][y]:
                    pixel.color = color

    def scrolling_text(self,
                       color: Color = Color(),
                       repetitions=1,
                       row_1="",
                       row_2=""):
        t = Text(row_1)
        t = t.array

        for rep in range(repetitions):
            for i in range(len(t)):
                for x, y, pixel in self.frame.fill():
                    if t[y][x]:
                        pixel.color = color
                self.render()
                t[i].append(t[i].pop(0))
                time.sleep(1)
                self.cleanup()

    def render(self):
        for position, color in self.frame.canvas():
            self.matrix.setPixelColor(position, color)
        self.matrix.show()

    def cleanup(self):
        self.color_wipe()
class LEDStrip:
    axis = None

    green = None
    red = None
    blue = None

    neopixel_Object = None
    LED_COUNT = 38  # Number of LED pixels.
    LED_PIN = None  # GPIO pin connected to the pixels (18 uses 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  # set to '1' for GPIOs 13, 19, 41, 45 or 53
    limitHeight = LED_COUNT

    def __init__(self, axis, GPIO_Pin, LED_COUNT=38, LED_FREQ_HZ=800000, LED_DMA=10, LED_BRIGHTNESS=255,
                 LED_INVERT=False, LED_CHANNEL=0):
        print("Initializing LED Strip on GPIO Pin " + str(GPIO_Pin))
        from neopixel import Adafruit_NeoPixel
        self.LED_COUNT = LED_COUNT
        self.LED_PIN = GPIO_Pin
        self.LED_FREQ_HZ = LED_FREQ_HZ
        self.LED_DMA = LED_DMA
        self.LED_BRIGHTNESS = LED_BRIGHTNESS
        self.LED_INVERT = LED_INVERT
        self.LED_CHANNEL = LED_CHANNEL
        self.green = 0
        self.red = 0
        self.blue = 0
        self.neopixel_Object = Adafruit_NeoPixel(self.LED_COUNT, self.LED_PIN, self.LED_FREQ_HZ, self.LED_DMA,
                                                 self.LED_INVERT, self.LED_BRIGHTNESS,
                                                 self.LED_CHANNEL)
        self.neopixel_Object.begin()
        updateColorsThread = Thread(target=self.updateColors)
        updateColorsThread.start()
        print("Started updateColors Thread")

    def updateColors(self):
        oldGreen = self.green
        oldRed = self.red
        oldBlue = self.blue
        limit = 40
        while True:
            if self.green != oldGreen or self.red != oldRed or self.blue != oldBlue:
                oldGreen = self.green
                oldRed = self.red
                oldBlue = self.blue
                print("Green: " + "{:>3}".format(str(self.green)) + ", Red: " + "{:>3}".format(
                    str(self.red)) + ", Blue: " + "{:>3}".format(str(self.blue)) + "\n")
                color = Color(self.green, self.red, self.blue)
                for i in range(self.neopixel_Object.numPixels()):
                    if i < self.limitHeight:
                        self.neopixel_Object.setPixelColor(i, color)
                self.neopixel_Object.show()
                time.sleep(50 / 1000.0)
class Lightstrip(object):
    def __init__(self, cfg):
        nps = cfg['neopixel']
        self.strip = Adafruit_NeoPixel(nps['led-count'], \
         nps['led-pin'], nps['led-freq-hz'], nps['led-dma'], \
         nps['led-invert'], nps['led-brightness'], nps['led-channel'])

        self.reversed = cfg['custom']['reversed']

        self.strip.begin()

    def _cleanup(self):
        self.strip._cleanup()

    def show(self):
        self.strip.show()

    # Sets the pixel without updating the strip
    #  Allows reversal of direction of the strip
    #  Ensures bounded pixel index from [0, numPixels)
    def setPixel(self, n, color):
        pixelNum = self.strip.numPixels() - 1 - n if self.reversed else n
        pixelNum %= self.strip.numPixels()
        self.strip.setPixelColor(pixelNum, color)

    # Sets the pixel and immediately updates the lightstrip visually
    def setPixelUpdate(self, n, color):
        self.setPixel(n, color)
        self.show()

    def setBrightness(self, n):
        self.strip.setBrightness(n)

    def getBrightness(self):
        self.strip.getBrightness()

    def setReversed(self, rev):
        self.reversed = rev

    def getReversed(self):
        return self.reversed

    def numPixels(self):
        return self.strip.numPixels()

    # The only animation I am baking into the lightstrip class because
    #  it has pretty universal importance among other animations and
    #  the runner class too
    def clear(self):
        for i in range(self.strip.numPixels()):
            self.setPixel(i, Color(0, 0, 0))
        self.show()

    def clearPixel(self, n):
        self.setPixel(n, Color(0, 0, 0))
Beispiel #11
0
class LightController(object):
    LED_COUNT = 43  # 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 = 5  # DMA channel to use for generating signal (try 5)
    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)

    def __init__(self):
        self.led_count = 43
        self.led_pin = 18
        self.leds = Adafruit_NeoPixel(self.LED_COUNT, self.LED_PIN,
                                      self.LED_FREQ_HZ, self.LED_DMA,
                                      self.LED_INVERT, self.LED_BRIGHTNESS)

    def cut_light_ranges(self, hue, disable_range):
        x = disable_range[0] * 255. / (255 - disable_range[1] +
                                       disable_range[0])
        if hue < x:
            hue *= (255 - disable_range[1] + disable_range[0]) / 255.
        else:
            hue = disable_range[1] + ((hue - x) *
                                      (255. - disable_range[1])) / (255. - x)
        return hue

    def cb_light(self, msg):
        disabled_range = [30, 100]
        hue = self.cut_light_ranges(msg.data, disabled_range)
        hue = hue / 255.  # Hue between (0., 1.)
        #r, g, b = map(int, hsv_to_rgb(hue, 1, 255))
        r, g, b = map(int, hsv_to_rgb(0, 0, msg.data))
        self.set_all(r, g, b)

    def set_all(self, r, g, b):
        for i in range(self.LED_COUNT):
            self.leds.setPixelColor(i, Color(g, r, b))
        self.leds.show()

    def run(self):
        try:
            self.leds.begin()
        except RuntimeError as e:
            raise RuntimeError(
                repr(e) +
                "\nAre you running this script with root permissions?")
        else:
            self.set_all(0, 0, 0)
            rospy.Subscriber("apex_playground/environment/light", UInt8,
                             self.cb_light)
            rospy.spin()
Beispiel #12
0
class PiWS281X(DriverBase):
    """
    Driver for controlling WS281X LEDs via the rpi_ws281x C-extension.
    Only supported on the Raspberry Pi 2 & 3
    """
    def __init__(self,
                 num,
                 gamma=gamma.NEOPIXEL,
                 c_order=ChannelOrder.RGB,
                 gpio=18,
                 ledFreqHz=800000,
                 ledDma=5,
                 ledInvert=False,
                 **kwds):
        """
        num - Number of LED pixels.
        gpio - GPIO pin connected to the pixels (must support PWM! GPIO 13 or 18 (pins 33 or 12) on RPi 3).
        ledFreqHz - LED signal frequency in hertz (800khz or 400khz)
        ledDma - DMA channel to use for generating signal (Between 1 and 14)
        ledInvert - True to invert the signal (when using NPN transistor level shift)
        """
        super().__init__(num, c_order=c_order, gamma=gamma, **kwds)
        self.gamma = gamma
        if gpio not in PIN_CHANNEL.keys():
            raise ValueError('{} is not a valid gpio option!')
        self._strip = Adafruit_NeoPixel(num, gpio, ledFreqHz, ledDma,
                                        ledInvert, 255, PIN_CHANNEL[gpio],
                                        0x081000)
        # Intialize the library (must be called once before other functions).
        self._strip.begin()

    def set_brightness(self, brightness):
        self._strip.setBrightness(brightness)
        return True

    def _compute_packet(self):
        self._render()
        data = self._buf
        self._packet = [
            tuple(data[(p * 3):(p * 3) + 3]) for p in range(len(data) // 3)
        ]

    def _send_packet(self):
        for i, p in enumerate(self._packet):
            self._strip.setPixelColor(i, NeoColor(*p))

        self._strip.show()
def main():
	global radien
	global streifen
	global pix
	global T
	n = 0			#Zählervariable
	neuesBild(path)
	gp.setmode(gp.BCM)          # Welche Nummern für die Pins verwendet werden
	gp.setwarnings(False)       # Keine Warnungen
	gp.setup(MAGNET_PIN, gp.IN) # Anschluss

	
	#Erschaffen des Led-Streifen-Objekts
	streifen = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, 
								 LED_INVERT, LED_BRIGHTNESS)


	streifen.begin()    #initialisieren des LED-Streifens
	startPrint()        #Drucken der Anfangseinstellungen



	while True:                             
		t1 = time()		#Startzeit der Umdrehung t1
		
		if gp.input(MAGNET_PIN) == False:	#Zeitmessung einmal je Umdrehung
			
			w = 2 * pi / T 	#Berrechnen der Aktuellen Winkelgeschwindigkeit
			
			while gp.input(MAGNET_PIN) == False:
				t = time() - t1 			#Ausrechnen der größe des Zeitabschnitts

				if t < 5:
					streifenBedienen(t, w)
					streifen.show()
				else:
					for i in range(0, LED_COUNT):
						streifen.setPixelColor(i, Color(0,0,0))
						streifen.show()
			n +=1
			if n > 3:				#jede dritte Umdrehung wird das bild neu in den Zwischenspeicher gepackt
				n = 0
				neuesBild("/home/pi/Bilder/Bild.")

			print("\b\b\b\b\b\b\b" + str(int(w * 0.3*3.6)) + " km/h")
			T = time() - t1              #Ausrechnen von T nach T = t2 - t1
Beispiel #14
0
    class __Instance:

        # LED strip configuration:
        LED_COUNT = 150 - 27  # 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 = 5  # DMA channel to use for generating signal (try 5)
        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)

        def __init__(self):
            random.seed()

            self.__strip = Adafruit_NeoPixel(self.LED_COUNT, self.LED_PIN,
                                             self.LED_FREQ_HZ, self.LED_DMA,
                                             self.LED_INVERT,
                                             self.LED_BRIGHTNESS)
            self.__strip.begin()

        LIT_COUNT = 10
        last = [0] * LIT_COUNT

        def twinkle(self):
            while True:
                for i in range(0, self.LIT_COUNT):
                    self.__strip.setPixelColor(self.last[i], color.Black())
                    self.last[i] = random.randint(0, self.__strip.numPixels())

                    self.__strip.setPixelColor(self.last[i], color.Random())

                self.__strip.show()
                util.delay(150)

        def walk(self):
            while True:
                for i in range(0, self.__strip.numPixels()):
                    self.__strip.setPixelColor(i, color.Random())
                    self.__strip.show()
                    util.delay(100.0)

                util.delay(750.0)

        def set_color(self, color):
            for i in range(0, self.__strip.numPixels()):
                self.__strip.setPixelColor(i, color)

            self.__strip.show()

        def cylon(self):
            red = 0
            for i in range(0, self.__strip.numPixels()):
                self.__strip.setPixelColor(i, color.Color(red, 0, 0))
                red += 1

            self.__strip.show()
class NeopixelSequencePlayer(SequencePlayer):
    def __init__(self):
        super().__init__()

        self.strip = Adafruit_NeoPixel(cfg.LED_COUNT, cfg.LED_DATA_PIN,
                                       cfg.LED_FREQ_HZ, cfg.LED_DMA,
                                       cfg.LED_INVERT, cfg.LED_BRIGHTNESS,
                                       cfg.LED_CHANNEL, cfg.LED_STRIP)
        self.strip.begin()

    def setrangecolor(self, start, end, color, write=True):
        super().setrangecolor(start, end, color, write)
        if write:
            self.strip.show()

    def setcolor(self, led, color, write=True):
        self.strip.setPixelColor(led, color.topixel())
        if write:
            self.strip.show()
Beispiel #16
0
def main():
    global radien
    global streifen
    global pix
    global T
    n = 0  #Zählervariable
    neuesBild(path)
    gp.setmode(gp.BCM)  # Welche Nummern für die Pins verwendet werden
    gp.setwarnings(False)  # Keine Warnungen
    gp.setup(MAGNET_PIN, gp.IN)  # Anschluss

    #Erschaffen des Led-Streifen-Objekts
    streifen = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA,
                                 LED_INVERT, LED_BRIGHTNESS)

    streifen.begin()  #initialisieren des LED-Streifens
    startPrint()  #Drucken der Anfangseinstellungen

    while True:
        t1 = time()  #Startzeit der Umdrehung t1

        if gp.input(MAGNET_PIN) == False:  #Zeitmessung einmal je Umdrehung

            w = 2 * pi / T  #Berrechnen der Aktuellen Winkelgeschwindigkeit

            while gp.input(MAGNET_PIN) == False:
                t = time() - t1  #Ausrechnen der größe des Zeitabschnitts

                if t < 5:
                    streifenBedienen(t, w)
                    streifen.show()
                else:
                    for i in range(0, LED_COUNT):
                        streifen.setPixelColor(i, Color(0, 0, 0))
                        streifen.show()
            n += 1
            if n > 3:  #jede dritte Umdrehung wird das bild neu in den Zwischenspeicher gepackt
                n = 0
                neuesBild("/home/pi/Bilder/Bild.")

            print("\b\b\b\b\b\b\b" + str(int(w * 0.3 * 3.6)) + " km/h")
            T = time() - t1  #Ausrechnen von T nach T = t2 - t1
Beispiel #17
0
class Control:
    def __init__(self):
        self.strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ,
                                       LED_DMA, LED_INVERT, LED_BRIGHTNESS, 0,
                                       ws.WS2812_STRIP)
        self.strip.begin()
        self.running = True

    def color_temp(self, temp, brightness=1.0):
        r, g, b = convert_K_to_RGB(temp)
        r = int(r * brightness)
        g = int(g * brightness)
        b = int(b * brightness)

        self.color(r, g, b)

    def color(self, r, g, b):
        color = Color(r, g, b)
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(i, color)

        while True:
            self.strip.show()
            if self.running:
                time.sleep(20 / 1000.0)
            else:
                return

    def rainbow(self):
        while True:
            for j in range(256):
                for i in range(self.strip.numPixels()):
                    self.strip.setPixelColor(i, wheel((i + j) & 255))

                self.strip.show()
                if self.running:
                    time.sleep(20 / 1000.0)
                else:
                    return

    def rainbow_onecolor(self):
        while True:
            for j in range(256):
                for i in range(self.strip.numPixels()):
                    self.strip.setPixelColor(i, wheel(j & 255))

                self.strip.show()
                if self.running:
                    time.sleep(20 / 1000.0)
                else:
                    return
class wordclock_display:
    """
    Class to display any content on the wordclock display
    Depends on the (individual) wordclock layout/wiring
    """

    def __init__(self, config, wci):
        """
        Initialization
        """
        # Get the wordclocks wiring-layout
        self.wcl = wiring.wiring(config)
        self.wci = wci
        try:
            default_brightness = config.getint('wordclock_display', 'brightness')
        except:
            default_brightness = 255
            print(
                'WARNING: Default brightness value not set in config-file: '
                'To do so, add a "brightness" between 1..255 to the [wordclock_display]-section.')

        if config.getboolean('wordclock', 'developer_mode'):
            from GTKstrip import GTKstrip
            self.strip = GTKstrip(wci)
            self.default_font = os.path.join('/usr/share/fonts/TTF/',
                                             config.get('wordclock_display', 'default_font') + '.ttf')
        else:
            try:
                from neopixel import Adafruit_NeoPixel, ws
                self.strip = Adafruit_NeoPixel(self.wcl.LED_COUNT, self.wcl.LED_PIN, self.wcl.LED_FREQ_HZ,
                                               self.wcl.LED_DMA, self.wcl.LED_INVERT, default_brightness , 0,
                                               ws.WS2811_STRIP_GRB)
            except:
                print('Update deprecated external dependency rpi_ws281x. '
                      'For details see also https://github.com/jgarff/rpi_ws281x/blob/master/python/README.md')

            self.default_font = os.path.join('/usr/share/fonts/truetype/freefont/',
                                             config.get('wordclock_display', 'default_font') + '.ttf')

        # Initialize the NeoPixel object
        self.strip.begin()

        self.default_fg_color = wcc.WWHITE
        self.default_bg_color = wcc.BLACK
        self.base_path = config.get('wordclock', 'base_path')

        # Choose language
        try:
            language = ''.join(config.get('wordclock_display', 'language'))
        except:
            # For backward compatibility
            language = ''.join(config.get('plugin_time_default', 'language'))

        print('  Setting language to ' + language + '.')
        if language == 'dutch':
            self.taw = time_dutch.time_dutch()
        elif language == 'english':
            self.taw = time_english.time_english()
        elif language == 'german':
            self.taw = time_german.time_german()
        elif language == 'german2':
            self.taw = time_german2.time_german2()
        elif language == 'swabian':
            self.taw = time_swabian.time_swabian()
        elif language == 'swabian2':
            self.taw = time_swabian2.time_swabian2()
        elif language == 'bavarian':
            self.taw = time_bavarian.time_bavarian()
        elif language == 'swiss_german':
            self.taw = time_swiss_german.time_swiss_german()
        elif language == 'swiss_german2':
            self.taw = time_swiss_german2.time_swiss_german2()
        else:
            print('Could not detect language: ' + language + '.')
            print('Choosing default: german')
            self.taw = time_german.time_german()

    def setPixelColor(self, pixel, color):
        """
        Sets the color for a pixel, while considering the brightness, set within the config file
        """
        self.strip.setPixelColor(pixel, color)

    def getBrightness(self):
        """
        Sets the color for a pixel, while considering the brightness, set within the config file
        """
        return self.strip.getBrightness()

    def setBrightness(self, brightness):
        """
        Sets the color for a pixel, while considering the brightness, set within the config file
        """
        self.strip.setBrightness(brightness)
        self.show()

    def setColorBy1DCoordinates(self, *args, **kwargs):
        """
        Sets a pixel at given 1D coordinates
        """
        return self.wcl.setColorBy1DCoordinates(*args, **kwargs)

    def setColorBy2DCoordinates(self, *args, **kwargs):
        """
        Sets a pixel at given 2D coordinates
        """
        return self.wcl.setColorBy2DCoordinates(*args, **kwargs)

    def get_wca_height(self):
        """
        Returns the height of the WCA
        """
        return self.wcl.WCA_HEIGHT

    def get_wca_width(self):
        """
        Returns the height of the WCA
        """
        return self.wcl.WCA_WIDTH

    def get_led_count(self):
        """
        Returns the overall number of LEDs
        """
        return self.wcl.LED_COUNT

    def dispRes(self):
        """
        Returns the resolution of the wordclock array as string
        E.g. to choose the correct resolution of animations and icons
        """
        return str(self.wcl.WCA_WIDTH) + 'x' + str(self.wcl.WCA_HEIGHT)

    def setColorToAll(self, color, includeMinutes=True):
        """
        Sets a given color to all leds
        If includeMinutes is set to True, color will also be applied to the minute-leds.
        """
        if includeMinutes:
            for i in range(self.wcl.LED_COUNT):
                self.setPixelColor(i, color)
        else:
            for i in self.wcl.getWcaIndices():
                self.setPixelColor(i, color)

    def setColorTemperatureToAll(self, temperature, includeMinutes=True):
        """
        Sets a color to all leds based on the provided temperature in Kelvin
        If includeMinutes is set to True, color will also be applied to the minute-leds.
        """
        self.setColorToAll(wcc.color_temperature_to_rgb(temperature), includeMinutes)

    def resetDisplay(self):
        """
        Reset display
        """
        self.setColorToAll(wcc.BLACK, True)

    def showIcon(self, plugin, iconName):
        """
        Dispays an icon with a specified name.
        The icon needs to be provided within the graphics/icons folder.
        """
        self.setImage(
            self.base_path + '/wordclock_plugins/' + plugin + '/icons/' + self.dispRes() + '/' + iconName + '.png')

    def setImage(self, absPathToImage):
        """
        Set image (provided as absolute path) to current display
        """
        img = Image.open(absPathToImage)
        width, height = img.size
        for x in range(0, width):
            for y in range(0, height):
                rgb_img = img.convert('RGB')
                r, g, b = rgb_img.getpixel((x, y))
                self.wcl.setColorBy2DCoordinates(self.strip, x, y, wcc.Color(r, g, b))
        self.show()

    def animate(self, plugin, animationName, fps=10, count=1, invert=False):
        """
        Runs an animation
        plugin: Plugin-name
        num_of_frames: Number of frames to be displayed
        count: Number of runs
        fps: frames per second
        invert: Invert order of animation
        """
        animation_dir = self.base_path + '/wordclock_plugins/' + plugin + '/animations/' + self.dispRes() + '/' + animationName + '/'
        num_of_frames = len([file_count for file_count in os.listdir(animation_dir)])

        if invert:
            animation_range = range(num_of_frames - 1, -1, -1)
        else:
            animation_range = range(0, num_of_frames)

        for _ in range(count):
            for i in animation_range:
                self.setImage(animation_dir + str(i).zfill(3) + '.png')
                if self.wci.waitForExit(1.0 / fps):
                    return

    def showText(self, text, font=None, fg_color=None, bg_color=None, fps=10, count=1):
        """
        Display text on display
        """
        if font is None:
            font = self.default_font
        if fg_color is None:
            fg_color = self.default_fg_color
        if bg_color is None:
            bg_color = self.default_bg_color

        text = '    ' + text + '    '

        fnt = fontdemo.Font(font, self.wcl.WCA_HEIGHT)
        text_width, text_height, text_max_descent = fnt.text_dimensions(text)
        text_as_pixel = fnt.render_text(text)

        # Display text count times
        for i in range(count):

            # Erase previous content
            self.setColorToAll(bg_color, includeMinutes=True)

            # Assure here correct rendering, if the text does not fill the whole display
            render_range = self.wcl.WCA_WIDTH if self.wcl.WCA_WIDTH < text_width else text_width
            for y in range(text_height):
                for x in range(render_range):
                    self.wcl.setColorBy2DCoordinates(self.strip, x, y,
                                                     fg_color if text_as_pixel.pixels[y * text_width + x] else bg_color)

            # Show first frame for 0.5 seconds
            self.show()
            if self.wci.waitForExit(0.5):
                return

            # Shift text from left to right to show all.
            for cur_offset in range(text_width - self.wcl.WCA_WIDTH + 1):
                for y in range(text_height):
                    for x in range(self.wcl.WCA_WIDTH):
                        self.wcl.setColorBy2DCoordinates(self.strip, x, y, fg_color if text_as_pixel.pixels[
                            y * text_width + x + cur_offset] else bg_color)
                self.show()
                if self.wci.waitForExit(1.0 / fps):
                    return

    def setMinutes(self, time, color):
        if time.minute % 5 != 0:
            for i in range(1, time.minute % 5 + 1):
                self.setPixelColor(self.wcl.mapMinutes(i), color)

    def show(self):
        """
        This function provides the current color settings to the LEDs
        """
        self.strip.show()
Beispiel #19
0
class PiWS281X(DriverBase):
    """
    Driver for controlling WS281X LEDs via the rpi_ws281x C-extension.
    Only supported on the Raspberry Pi 2, 3, and Zero

    This driver needs to be run as sudo and requires the rpi_ws281x C extension.

    Install rpi_ws281x with the following shell commands:

        git clone https://github.com/jgarff/rpi_ws281x.git
        cd rpi_ws281x

        sudo apt-get install python-dev swig scons
        sudo scons

        cd python
        # If using default system python3
        sudo python3 setup.py build install
        # If using virtualenv, enter env then run
        python setup.py build install

    Provides the same parameters of :py:class:`.driver_base.DriverBase` as
    well as those below:

    :param int gpio: GPIO pin to output to. Typically 18 or 13
    :param int ledFreqHz: WS2812B base data frequency in Hz. Only change to
        400000 if using very old WS218B LEDs
    :param int ledDma: DMA channel to use for generating signal
                       (between 1 and 14)
    :param bool ledInvert: True to invert the signal
                       (when using NPN transistor level shift)
    """
    def __init__(self,
                 num,
                 gamma=gamma.NEOPIXEL,
                 c_order="RGB",
                 gpio=18,
                 ledFreqHz=800000,
                 ledDma=5,
                 ledInvert=False,
                 color_channels=3,
                 brightness=255,
                 **kwds):

        if not NeoColor:
            raise ValueError(WS_ERROR)
        super().__init__(num, c_order=c_order, gamma=gamma, **kwds)
        self.gamma = gamma
        if gpio not in PIN_CHANNEL.keys():
            raise ValueError('{} is not a valid gpio option!')
        try:
            strip_type = STRIP_TYPES[color_channels]
        except:
            raise ValueError('In PiWS281X, color_channels can only be 3 or 4')

        self._strip = Adafruit_NeoPixel(num, gpio, ledFreqHz, ledDma,
                                        ledInvert, brightness,
                                        PIN_CHANNEL[gpio], strip_type)
        # Intialize the library (must be called once before other functions).
        try:
            self._strip.begin()
        except RuntimeError as e:
            if os.geteuid():
                if os.path.basename(sys.argv[0]) in ('bp', 'bibliopixel'):
                    command = ['bp'] + sys.argv[1:]
                else:
                    command = ['python'] + sys.argv
                error = SUDO_ERROR.format(command=' '.join(command))
                e.args = (error, ) + e.args
            raise

    def set_brightness(self, brightness):
        self._strip.setBrightness(brightness)
        return True

    def _compute_packet(self):
        self._render()
        data = self._buf
        self._packet = [
            tuple(data[(p * 3):(p * 3) + 3]) for p in range(len(data) // 3)
        ]

    def _send_packet(self):
        for i, p in enumerate(self._packet):
            self._strip.setPixelColor(i, NeoColor(*p))

        self._strip.show()
class wordclock_display:
    """
    Class to display any content on the wordclock display
    Depends on the (individual) wordclock layout/wiring
    """
    def __init__(self, config, wci):
        """
        Initialization
        """
        # Get the wordclocks wiring-layout
        self.wcl = wiring.wiring(config)
        self.wci = wci
        self.config = config
        self.base_path = config.get('wordclock', 'base_path')
        max_brightness = 255

        try:
            self.setBrightness(config.getint('wordclock_display',
                                             'brightness'))
        except:
            self.brightness = max_brightness
            print(
                'WARNING: Default brightness value not set in config-file: '
                'To do so, add a "brightness" between 1..255 to the [wordclock_display]-section.'
            )

        if config.getboolean('wordclock', 'developer_mode'):
            from GTKstrip import GTKstrip
            self.strip = GTKstrip(wci)
            self.default_font = 'wcfont.ttf'
        else:
            try:
                from neopixel import Adafruit_NeoPixel, ws
                self.strip = Adafruit_NeoPixel(
                    self.wcl.LED_COUNT, self.wcl.LED_PIN, self.wcl.LED_FREQ_HZ,
                    self.wcl.LED_DMA, self.wcl.LED_INVERT, max_brightness, 0,
                    ws.WS2811_STRIP_GRB)
            except:
                print(
                    'Update deprecated external dependency rpi_ws281x. '
                    'For details see also https://github.com/jgarff/rpi_ws281x/blob/master/python/README.md'
                )

            if config.get('wordclock_display', 'default_font') == 'wcfont':
                self.default_font = self.base_path + '/wcfont.ttf'
            else:
                self.default_font = os.path.join(
                    '/usr/share/fonts/truetype/freefont/',
                    config.get('wordclock_display', 'default_font') + '.ttf')

        # Initialize the NeoPixel object
        self.strip.begin()

        self.default_fg_color = wcc.WWHITE
        self.default_bg_color = wcc.BLACK

        # Choose language
        try:
            language = ''.join(config.get('wordclock_display', 'language'))
        except:
            # For backward compatibility
            language = ''.join(config.get('plugin_time_default', 'language'))

        print('  Setting language to ' + language + '.')
        if language == 'dutch':
            self.taw = time_dutch.time_dutch()
        elif language == 'english':
            self.taw = time_english.time_english()
        elif language == 'english_c3jr':
            self.taw = time_english_c3jr.time_english()
        elif language == 'german':
            self.taw = time_german.time_german()
        elif language == 'german2':
            self.taw = time_german2.time_german2()
        elif language == 'swabian':
            self.taw = time_swabian.time_swabian()
        elif language == 'swabian2':
            self.taw = time_swabian2.time_swabian2()
        elif language == 'bavarian':
            self.taw = time_bavarian.time_bavarian()
        elif language == 'swiss_german':
            self.taw = time_swiss_german.time_swiss_german()
        elif language == 'swiss_german2':
            self.taw = time_swiss_german2.time_swiss_german2()
        else:
            print('Could not detect language: ' + language + '.')
            print('Choosing default: german')
            self.taw = time_german.time_german()

    def setPixelColor(self, pixel, color):
        """
        Sets the color for a pixel, while considering the brightness, set within the config file
        """
        self.strip.setPixelColor(pixel, color)

    def getBrightness(self):
        """
        Sets the color for a pixel, while considering the brightness, set within the config file
        """
        return self.brightness

    def setBrightness(self, brightness):
        """
        Sets the color for a pixel, while considering the brightness, set within the config file
        """
        brightness_before = self.getBrightness()
        brightness = max(min(255, brightness), 0)

        for i in range(self.wcl.LED_COUNT):
            color = self.getPixelColor(i)
            color = (color / brightness_before) ^ (1 / 2.2) * brightness
            self.setPixelColor(i, color)

        self.brightness = brightness
        self.show()

    def setColorBy1DCoordinates(self, *args, **kwargs):
        """
        Sets a pixel at given 1D coordinates
        """
        return self.wcl.setColorBy1DCoordinates(*args, **kwargs)

    def setColorBy2DCoordinates(self, *args, **kwargs):
        """
        Sets a pixel at given 2D coordinates
        """
        return self.wcl.setColorBy2DCoordinates(*args, **kwargs)

    def get_wca_height(self):
        """
        Returns the height of the WCA
        """
        return self.wcl.WCA_HEIGHT

    def get_wca_width(self):
        """
        Returns the width of the WCA
        """
        return self.wcl.WCA_WIDTH

    def get_led_count(self):
        """
        Returns the overall number of LEDs
        """
        return self.wcl.LED_COUNT

    def dispRes(self):
        """
        Returns the resolution of the wordclock array as string
        E.g. to choose the correct resolution of animations and icons
        """
        return str(self.wcl.WCA_WIDTH) + 'x' + str(self.wcl.WCA_HEIGHT)

    def setColorToAll(self, color, includeMinutes=True):
        """
        Sets a given color to all leds
        If includeMinutes is set to True, color will also be applied to the minute-leds.
        """
        if includeMinutes:
            for i in range(self.wcl.LED_COUNT):
                self.setPixelColor(i, color)
        else:
            for i in self.wcl.getWcaIndices():
                self.setPixelColor(i, color)

    def setColorTemperatureToAll(self, temperature, includeMinutes=True):
        """
        Sets a color to all leds based on the provided temperature in Kelvin
        If includeMinutes is set to True, color will also be applied to the minute-leds.
        """
        self.setColorToAll(wcc.color_temperature_to_rgb(temperature),
                           includeMinutes)

    def resetDisplay(self):
        """
        Reset display
        """
        self.setColorToAll(wcc.BLACK, True)

    def showIcon(self, plugin, iconName):
        """
        Dispays an icon with a specified name.
        The icon needs to be provided within the graphics/icons folder.
        """
        self.setImage(self.base_path + '/wordclock_plugins/' + plugin +
                      '/icons/' + self.dispRes() + '/' + iconName + '.png')

    def setImage(self, absPathToImage):
        """
        Set image (provided as absolute path) to current display
        """
        img = Image.open(absPathToImage)
        width, height = img.size
        for x in range(0, width):
            for y in range(0, height):
                rgb_img = img.convert('RGB')
                r, g, b = rgb_img.getpixel((x, y))
                self.wcl.setColorBy2DCoordinates(self.strip, x, y,
                                                 wcc.Color(r, g, b))
        self.show()

    def animate(self, plugin, animationName, fps=10, count=1, invert=False):
        """
        Runs an animation
        plugin: Plugin-name
        num_of_frames: Number of frames to be displayed
        count: Number of runs
        fps: frames per second
        invert: Invert order of animation
        """
        animation_dir = self.base_path + '/wordclock_plugins/' + plugin + '/animations/' + self.dispRes(
        ) + '/' + animationName + '/'
        num_of_frames = len(
            [file_count for file_count in os.listdir(animation_dir)])

        if invert:
            animation_range = range(num_of_frames - 1, -1, -1)
        else:
            animation_range = range(0, num_of_frames)

        for _ in range(count):
            for i in animation_range:
                self.setImage(animation_dir + str(i).zfill(3) + '.png')
                if self.wci.waitForExit(1.0 / fps):
                    return

    def showText(self,
                 text,
                 font=None,
                 fg_color=None,
                 bg_color=None,
                 fps=10,
                 count=1):
        """
        Display text on display
        """
        if font is None:
            font = self.default_font
        if fg_color is None:
            fg_color = self.default_fg_color
        if bg_color is None:
            bg_color = self.default_bg_color

        text = '    ' + text + '    '

        fnt = fontdemo.Font(font, self.wcl.WCA_HEIGHT)

        text_width, text_height, text_max_descent = fnt.text_dimensions(text)
        text_as_pixel = fnt.render_text(text)

        # Display text count times
        for i in range(count):

            # Erase previous content
            self.setColorToAll(bg_color, includeMinutes=True)

            # Assure here correct rendering, if the text does not fill the whole display
            render_range = self.wcl.WCA_WIDTH if self.wcl.WCA_WIDTH < text_width else text_width
            for y in range(text_height):
                for x in range(render_range):
                    self.wcl.setColorBy2DCoordinates(
                        self.strip, x, y,
                        fg_color if text_as_pixel.pixels[y * text_width +
                                                         x] else bg_color)

            # Show first frame for 0.5 seconds
            self.show()
            if self.wci.waitForExit(0.5):
                return

            # Shift text from left to right to show all.
            for cur_offset in range(text_width - self.wcl.WCA_WIDTH + 1):
                for y in range(text_height):
                    for x in range(self.wcl.WCA_WIDTH):
                        self.wcl.setColorBy2DCoordinates(
                            self.strip, x, y, fg_color
                            if text_as_pixel.pixels[y * text_width + x +
                                                    cur_offset] else bg_color)
                self.show()
                if self.wci.waitForExit(1.0 / fps):
                    return

    def setMinutes(self, time, color):
        if time.minute % 5 != 0:
            for i in range(1, time.minute % 5 + 1):
                self.setPixelColor(self.wcl.mapMinutes(i), color)

    def show(self):
        """
        This function provides the current color settings to the LEDs
        """
        self.strip.show()
def set_led(i, r, g, b):
    if i < LED_COUNT:
        ws2812.setPixelColorRGB(i, r, g, b)


def readSensor():
    lastBuf[0] = inBuf[0]
    lastBuf[1] = inBuf[1]
    for i in range(0, 2):
        adc = spi.xfer2([1, (8 + i) << 4, 0])  # request channel
        inBuf[i] = (adc[1] & 3) << 8 | adc[2]  # join two bytes together
    difBuf[0] = abs(inBuf[0] - lastBuf[0])  # work out changes
    difBuf[1] = abs(inBuf[1] - lastBuf[1])


def initHardware():
    global spi, lastX, lastY, ch0Low, ch1Low
    spi = spidev.SpiDev()
    spi.open(0, 0)
    spi.max_speed_hz = 1000000


# Main program logic:
if __name__ == '__main__':
    try:
        main()
    except:  # clear up the LEDs
        wipe()
        ws2812.show()
Beispiel #22
0
def exc():
    import os
    import json
    import math
    import time
    from copy import deepcopy
    from neopixel import Adafruit_NeoPixel
    basedir = os.path.dirname(os.path.realpath(__file__))

    steps = 120
    neopixel = Adafruit_NeoPixel(1, 18)
    neopixel.begin()

    setting = {'threat': 0, 'cautioning': 0, 'optimum': 1}
    changelog = [0, 0, 0]

    if setting['threat'] > 0:
        changelog[0] = 255
    elif setting['cautioning'] > 0:
        changelog[0] = 255
        changelog[1] = 255
    elif setting['optimum'] > 0:
        changelog[1] = 255

    if os.path.isfile(basedir + '/ledstate.json'):
        with open(basedir + '/ledstate.json', 'r') as out:
            current = json.loads(out.read())
    else:
        raw = neopixel.getPixelColor(0)
        current = []

        for _ in range(3):
            calc = divmod(raw, 256)
            raw = calc[0]
            current.append(calc[1])

        current = current[::-1]
    print(current)
    bcurrent = []
    bchange = []

    for pointer in range(len(current)):
        bcurrent.append(
            True if current[pointer] > changelog[pointer] else False)
        bchange.append(
            True if current[pointer] != changelog[pointer] else False)

    old = deepcopy(current)
    for i in range(0, steps + 1):
        color = []
        for pointer in range(len(bchange)):
            if bchange[pointer]:
                if not bcurrent[pointer]:
                    x = i
                    offset = current[pointer]
                else:
                    x = steps - i
                    offset = changelog[pointer]
                color.append(offset + int(
                    abs(current[pointer] - changelog[pointer]) / steps * x))
                # color.append(offset + int(math.cos((1 / steps) * math.pi * x) * (abs(current[pointer] - changelog[pointer]) / 2) + (abs(current[pointer] - changelog[pointer]) / 2)))
            else:
                color.append(old[pointer])
        print(color)
        neopixel.setPixelColorRGB(0, color[0], color[1], color[2])
        neopixel.show()
        old = deepcopy(color)
        # time.sleep(1 / 30)
        print(color)

    with open(basedir + '/ledstate.json', 'w') as out:
        out.write(json.dumps(old))
Beispiel #23
0
class ColoramaDisplay(ApplicationSession):
    @inlineCallbacks
    def onJoin(self, details):

        self._serial = get_serial()
        self._prefix = 'io.crossbar.demo.iotstarterkit.{}.pixelstrip'.format(
            self._serial)

        self.log.info("Crossbar.io IoT Starterkit Serial No.: {serial}",
                      serial=self._serial)
        self.log.info("ColoramaDisplay connected: {details}", details=details)

        # get custom configuration
        cfg = self.config.extra

        self._leds = Adafruit_NeoPixel(cfg['led_count'], cfg['led_pin'],
                                       cfg['led_freq_hz'], cfg['led_dma'],
                                       cfg['led_invert'],
                                       cfg['led_brightness'])

        self._leds.begin()

        for proc in [
            (self.set_color, 'set_color'),
            (self.get_color, 'get_color'),
            (self.flash, 'flash'),
            (self.lightshow, 'lightshow'),
            (self.color_wipe, 'color_wipe'),
            (self.theater_chase, 'theater_chase'),
            (self.rainbow, 'rainbow'),
            (self.rainbow_cycle, 'rainbow_cycle'),
            (self.theater_chaserainbow, 'theater_chaserainbow'),
        ]:
            yield self.register(proc[0], '{}.{}'.format(self._prefix, proc[1]))

        self.flash()

        self.log.info("ColoramaDisplay ready!")

    @inlineCallbacks
    def flash(self, delay=50, repeat=5):
        delay = float(delay) / 1000.
        for i in range(repeat):
            self.set_color(0xe1, 0xda, 0x05)
            yield sleep(2 * delay)
            self.set_color(0x52, 0x42, 0x00)
            yield sleep(delay)

    @inlineCallbacks
    def lightshow(self):
        # Color wipe animations.
        yield self.color_wipe(255, 0, 0)  # Red wipe
        yield self.color_wipe(0, 255, 0)  # Blue wipe
        yield self.color_wipe(0, 0, 255)  # Green wipe
        # Theater chase animations.
        yield self.theater_chase(127, 127, 127)  # White theater chase
        yield self.theater_chase(127, 0, 0)  # Red theater chase
        yield self.theater_chase(0, 0, 127)  # Blue theater chase
        # Rainbow animations.
        yield self.rainbow()
        yield self.rainbow_cycle()
        #yield self.theater_chase_rainbow()
        yield self.flash()

    # Define functions which animate LEDs in various ways.
    @inlineCallbacks
    def color_wipe(self, r, g, b, wait_ms=50):
        """Wipe color across display a pixel at a time."""
        for i in range(self._leds.numPixels()):
            self.set_color(r, g, b, i)
            yield sleep(wait_ms / 1000.0)

    @inlineCallbacks
    def theater_chase(self, r, g, b, wait_ms=50, iterations=10):
        """Movie theater light style chaser animation."""
        for j in range(iterations):
            for q in range(3):
                for i in range(0, self._leds.numPixels(), 3):
                    self.set_color(r, g, b, i + q)
                yield sleep(wait_ms / 1000.0)
                for i in range(0, self._leds.numPixels(), 3):
                    self.set_color(0, 0, 0, i + q)

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

    @inlineCallbacks
    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._leds.numPixels()):
                r, g, b = self.wheel((i + j) & 255)
                self.set_color(r, g, b, i)
            yield sleep(wait_ms / 1000.0)

    @inlineCallbacks
    def rainbow_cycle(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._leds.numPixels()):
                r, g, b = self.wheel(((i * 256 / self._leds.numPixels()) + j)
                                     & 255)
                self.set_color(r, g, b, i)
            yield sleep(wait_ms / 1000.0)

    @inlineCallbacks
    def theater_chaserainbow(self, wait_ms=50):
        """Rainbow movie theater light style chaser animation."""
        for j in range(256):
            for q in range(3):
                for i in range(0, self._leds.numPixels(), 3):
                    r, g, b = self.wheel((i + j) % 255)
                    self.set_color(r, g, b, i + q)
                yield sleep(wait_ms / 1000.0)
                for i in range(0, self._leds.numPixels(), 3):
                    self.set_color(0, 0, 0, i)

    def set_color(self, red, green, blue, k=None):
        if k is None:
            for i in range(self._leds.numPixels()):
                # FIXME: not sure, but we need to swap this here. maybe it is the specific neopixels?
                self._leds.setPixelColorRGB(i, green, red, blue)
                color_change = {'led': i, 'r': red, 'g': green, 'b': blue}
                self.publish('{}.on_color_set'.format(self._prefix),
                             color_change)
        else:
            # FIXME: not sure, but we need to swap this here. maybe it is the specific neopixels?
            self._leds.setPixelColorRGB(k, green, red, blue)
            color_change = {'led': k, 'r': red, 'g': green, 'b': blue}
            self.publish('{}.on_color_set'.format(self._prefix), color_change)
        self._leds.show()

    def get_color(self, k):
        c = self._leds.getPixelColor(k)
        color = {
            'g': c >> 16,
            'r': (c >> 8) & 0xff,
            'b': c & 0xff,
        }
        return color

    def onLeave(self, details):
        self.log.info("Session closed: {details}", details=details)
        self.disconnect()

    def onDisconnect(self):
        self.log.info("Connection closed")
        for i in range(self._leds.numPixels()):
            self._leds.setPixelColorRGB(i, 0, 0, 0)
        self._leds.show()
        try:
            reactor.stop()
        except ReactorNotRunning:
            pass
Beispiel #24
0
class RPiMaze(MazeGame):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # Set up NeoPixel
        self.np = Adafruit_NeoPixel(NUM_PIXELS, GPIO_PIN, brightness=INTENSITY)
        self.np.begin()

        self.led_grid = led_grid.LEDGrid(self.np, grid.SerpentinePattern.TOP_RIGHT,
                                         width=MATRIX_WIDTH, height=MATRIX_HEIGHT)

    @staticmethod
    def hexcolor_to_rgb(colorstr):
        # https://stackoverflow.com/a/29643643 TODO: abstract this out some more
        color = tuple(int(colorstr.lstrip('#')[i:i+2], 16) for i in (0, 2, 4))
        print("%s: %s" % (colorstr, str(color)))
        return color

    def draw_point_at(self, x, y, color):
        try:
            self.led_grid.set(x, y, color, allowOverwrite=True)
        except IndexError:
            pass

    def _draw_walls(self, wall_points_to_draw):
        for point in wall_points_to_draw:
            #print("Drawing LED point %s, %s as a wall" % (point[0], point[1]))
            self.draw_point_at(point[0], point[1], (255, 255, 255))

    def draw_maze_leds(self):
        """
        Draws the maze on an LED strip.
        """
        for pixel in range(NUM_PIXELS):
            self.np.setPixelColorRGB(pixel, 0, 0, 0)
        for ypos, row in enumerate(self.maze.by_rows()):
            for xpos, point in enumerate(row):
                if point.is_finish:
                    color = self.hexcolor_to_rgb(self.FINISH_COLOR)
                elif point.is_start:
                    color = self.hexcolor_to_rgb(self.START_COLOR)
                else:
                    # Empty tile
                    color = (0, 0, 0)

                for sprite in self.sprites:
                    if sprite.x == xpos and sprite.y == ypos:
                        color = self.hexcolor_to_rgb(sprite.color)
                        print("Setting color to %s for sprite %s at %s, %s" % (color, sprite, xpos, ypos))

                if point.is_selected:
                    color = self.hexcolor_to_rgb(self.SELECTED_COLOR)

                led_xpos = xpos * 2
                led_ypos = ypos * 2
                #print("Translating player position (%s, %s) into LED position (%s, %s)" % (xpos, ypos, led_xpos, led_ypos))

                wall_points_to_draw = {
                    (led_xpos-1, led_ypos-1),
                    (led_xpos-1, led_ypos+1),
                    (led_xpos+1, led_ypos-1),
                    (led_xpos+1, led_ypos+1)
                }
                paths = point.paths
                if 'north' not in paths:
                    wall_points_to_draw.add((led_xpos, led_ypos-1))
                if 'south' not in paths:
                    wall_points_to_draw.add((led_xpos, led_ypos+1))
                if 'east' not in paths:
                    wall_points_to_draw.add((led_xpos+1, led_ypos))
                if 'west' not in paths:
                    wall_points_to_draw.add((led_xpos-1, led_ypos))

                self._draw_walls(wall_points_to_draw)
                self.draw_point_at(led_xpos, led_ypos, color)
        self.np.show()
        self.led_grid.show()

    def draw_maze(self, *args, **kwargs):
        super().draw_maze(*args, **kwargs)
        self.draw_maze_leds()
        return True
Beispiel #25
0
  def run(steps=120):
    result = VariousTools.offline_check('generalleds', hardware=False)
    changelog = [0, 0, 0]
    if result:
      setting = {'threat': 0, 'cautioning': 0, 'optimum': 0}
      plant = Plant.get(localhost=True)

      all_status = SensorStatus.select().where(SensorStatus.plant == plant)

      for status in all_status:
        setting[status.level.label] += 1

      if setting['threat'] > 0:
        changelog[0] = 255
      elif setting['cautioning'] > 0:
        changelog[0] = 255
        changelog[1] = 255
      elif setting['optimum'] > 0:
        changelog[1] = 255

    basedir = os.path.dirname(os.path.realpath(__file__))
    neopixel = Adafruit_NeoPixel(1, 18)
    neopixel.begin()

    if os.path.isfile(basedir + '/ledstate.json'):
      with open(basedir + '/ledstate.json', 'r') as out:
        current = json.loads(out.read())
    else:
      raw = neopixel.getPixelColor(0)
      current = []

      for _ in range(3):
        calc = divmod(raw, 256)
        raw = calc[0]
        current.append(calc[1])

      current = current[::-1]

    if changelog == current:
      return True

    bcurrent = []
    bchange = []

    for pointer in range(len(current)):
      bcurrent.append(True if current[pointer] >= changelog[pointer] else False)
      bchange.append(True if current[pointer] != changelog[pointer] else False)

    old = deepcopy(current)
    for i in range(0, steps + 1):
      color = []
      for pointer in range(len(bchange)):
        if bchange[pointer]:
          if not bcurrent[pointer]:
            x = i
            offset = current[pointer]
          else:
            x = steps - i
            offset = changelog[pointer]
          color.append(offset + int(abs(current[pointer] - changelog[pointer]) / steps * x))
        else:
          color.append(old[pointer])

      print(color)
      neopixel.setPixelColorRGB(0, color[0], color[1], color[2])
      neopixel.show()
      old = deepcopy(color)
      time.sleep(1 / 15)

    with open(basedir + '/ledstate.json', 'w') as out:
      out.write(json.dumps(color))

    time.sleep(1)
    neopixel.setPixelColorRGB(0, changelog[0], changelog[1], changelog[2])
    neopixel.show()

    return True
Beispiel #26
0
class PiWS281X(DriverBase):
    """
    Driver for controlling WS281X LEDs via the rpi_ws281x C-extension.
    Only supported on the Raspberry Pi 2, 3, and Zero

    This driver needs to be run as sudo and requires the rpi_ws281x C extension.

    Install rpi_ws281x with the following shell commands:

        git clone https://github.com/jgarff/rpi_ws281x.git
        cd rpi_ws281x

        sudo apt-get install python-dev swig scons
        sudo scons

        cd python
        # If using default system python3
        sudo python3 setup.py build install
        # If using virtualenv, enter env then run
        python setup.py build install

    Provides the same parameters of :py:class:`.driver_base.DriverBase` as
    well as those below:

    :param int gpio: GPIO pin to output to. Typically 18 or 13
    :param int ledFreqHz: WS2812B base data frequency in Hz. Only change to
        400000 if using very old WS218B LEDs
    :param int ledDma: DMA channel to use for generating signal (Between 1 and 14)
    :param bool ledInvert: True to invert the signal (when using NPN transistor level shift)
    """
    # Including follow as comment as URLs in docstrings don't play well with sphinx
    # Discussion re: running as sudo
    # https://groups.google.com/d/msg/maniacal-labs-users/6hV-2_-Xmqc/wmWJK709AQAJ
    # https://github.com/jgarff/rpi_ws281x/blob/master/python/neopixel.py#L106

    def __init__(
            self, num, gamma=gamma.NEOPIXEL, c_order="RGB", gpio=18,
            ledFreqHz=800000, ledDma=5, ledInvert=False,
            color_channels=3, brightness=255, **kwds):

        if not NeoColor:
            raise ValueError(WS_ERROR)
        super().__init__(num, c_order=c_order, gamma=gamma, **kwds)
        self.gamma = gamma
        if gpio not in PIN_CHANNEL.keys():
            raise ValueError('{} is not a valid gpio option!')
        try:
            strip_type = STRIP_TYPES[color_channels]
        except:
            raise ValueError('In PiWS281X, color_channels must be either 3 or 4')

        self._strip = Adafruit_NeoPixel(
            num, gpio, ledFreqHz, ledDma, ledInvert, brightness,
            PIN_CHANNEL[gpio], strip_type)
        # Intialize the library (must be called once before other functions).
        try:
            self._strip.begin()
        except RuntimeError as e:
            if os.geteuid():
                if os.path.basename(sys.argv[0]) in ('bp', 'bibliopixel'):
                    command = ['bp'] + sys.argv[1:]
                else:
                    command = ['python'] + sys.argv
                error = SUDO_ERROR.format(command=' '.join(command))
                e.args = (error,) + e.args
            raise

    def set_brightness(self, brightness):
        self._strip.setBrightness(brightness)
        return True

    def _compute_packet(self):
        self._render()
        data = self._buf
        self._packet = [tuple(data[(p * 3):(p * 3) + 3]) for p in range(len(data) // 3)]

    def _send_packet(self):
        for i, p in enumerate(self._packet):
            self._strip.setPixelColor(i, NeoColor(*p))

        self._strip.show()
class LedController:

    global debug

    def __init__(self, display_mode:str, number_of_led_strips:int, number_of_leds_per_strip:int):

        self.current_beat_index = 0

        self.note_led_rows = []

        self.number_of_led_strips = number_of_led_strips
        self.number_of_leds_per_strip = number_of_leds_per_strip

        # holds the rgb values of each led
        self.all_colors_as_str = []
        self.all_led_rgb_value_lists = []

        # colors as [R, G, B]
        self.color_dict = {
            'off': [0, 0, 0],
            'white': [255, 255, 255],
            'red': [255, 0, 0],
            'blue': [0, 0, 255],
            'green': [0, 255, 0]
        }

        # choose whether or not to highlight the current beat and dim the rest = 'highlight'
        # or only show the colors of the current beat = 'only_current'
        self.display_mode = display_mode
        # self.display_mode = 'only_current'
        # self.display_mode = 'highlight'
        # the other leds will be divided by this factor
        self.display_mode_highlight_factor = 10

        self.led_strip = None

        # led strip settings
        self.number_of_leds_total = self.number_of_led_strips * self.number_of_leds_per_strip
        self.led_pin = 21  # uses PCM
        self.frequency_hz = 800000
        self.dma = 10
        self.led_brightness = 100
        self.led_inverted = False
        self.led_pin_channel = 0

        if debug:
            print('Settings for LedController(): ')
            print('Mode: ', self.display_mode)
            print('Brightness: ', self.led_brightness)
            print('Number of led strips: ', self.number_of_led_strips)
            print('Number of leds per strip: ', self.number_of_leds_per_strip)
            print('Total number of leds: ', self.number_of_leds_total)

    def initialize_led_strip(self):
        self.led_strip = Adafruit_NeoPixel(num=self.number_of_leds_total,
                                           pin=self.led_pin,
                                           freq_hz=self.frequency_hz,
                                           dma=self.dma,
                                           invert=self.led_inverted,
                                           brightness=self.led_brightness,
                                           channel=self.led_pin_channel
                                           )
        self.led_strip.begin()

        if debug:
            print('\nInitialized Led strip... Obj: ', self.led_strip)
            print()

    def remove_strip_obj(self):
        self.led_strip = None

    def set_current_beat(self, beat:int):
        self.current_beat_index = beat - 1

    # will set leds to be the colors from the led obj, depending on the display mode
    def set_led_colors(self):
        # choose whether to only show the current beat leds, or to highlight it

        if debug:
            print('Setting led colors... using display mode: ', self.display_mode)

        if self.display_mode == 'only_current':
            if debug:
                print('Mode is ', self.display_mode)
            self.only_show_colors_from_current_beat()
            self.convert_color_str_to_rgb()
        elif self.display_mode == 'highlight':
            if debug:
                print('Mode is ', self.display_mode)
            self.highlight_current_beat_leds()

    def only_show_colors_from_current_beat(self):
        index = 0
        for note_led_row in self.note_led_rows:
            if index == self.current_beat_index:
                for note_led_container in note_led_row.row:
                    led = note_led_container.led
                    if led.is_displayed():
                        self.all_colors_as_str.append(led.get_color())
                    else:
                        self.all_colors_as_str.append('off')
            else:
                for note_led_container in note_led_row.row:
                        self.all_colors_as_str.append('off')
            index += 1

    # convert color str to lists of three rgb values
    def convert_color_str_to_rgb(self):
        for color_str in self.all_colors_as_str:
            rgb_list = self.color_dict[color_str]
            self.all_led_rgb_value_lists.append(rgb_list)

    # the leds of the current beat will be displayed at full brightness, the other beats at half
    def highlight_current_beat_leds(self):
        index = 0
        for note_led_row in self.note_led_rows:
            if index == self.current_beat_index:
                for note_led_container in note_led_row.row:
                    led = note_led_container.led
                    if led.is_displayed():
                        color_str = led.get_color()
                        self.all_colors_as_str.append(color_str)
                        self.add_color_to_rgb_list(color=color_str)
                    else:
                        color_str = 'off'
                        self.all_colors_as_str.append(color_str)
                        self.add_color_to_rgb_list(color=color_str)
            else:
                for note_led_container in note_led_row.row:
                    led = note_led_container.led
                    if led.is_displayed():
                        color_str = led.get_color()
                        self.all_colors_as_str.append(color_str)
                        self.add_color_to_rgb_list(color=color_str, reduced_brightness=True)
                    else:
                        color_str = 'off'
                        self.all_colors_as_str.append(color_str)
                        self.add_color_to_rgb_list(color=color_str)
            index += 1

    def add_color_to_rgb_list(self, color:str, reduced_brightness=False):
        rgb_list = self.color_dict[color]
        output_list = []
        # if reduced brightness we divide by a factor
        if reduced_brightness:
            index = 0
            for rgb_val in rgb_list:
                if not (rgb_val == 0):
                    rgb_val = int(float(rgb_val) / float(self.display_mode_highlight_factor))
                output_list.append(rgb_val)
                index += 1
        else:
            output_list = rgb_list
        self.all_led_rgb_value_lists.append(output_list)

    # set the values for each led in the strip obj
    def update_led_strip_colors(self):
        led_index = 0
        for rgb_list in self.all_led_rgb_value_lists:
            r = rgb_list[0]
            g = rgb_list[1]
            b = rgb_list[2]
            self.led_strip.setPixelColorRGB(n=led_index, red=r, green=g, blue=b)
            led_index += 1

    # actually output the color values to the strip
    def display_updated_leds(self):
        if debug:
            print('Updating the output of the leds')
        self.led_strip.show()

    def clear_led_strip(self):
        for i in range(self.number_of_leds_total):
            self.led_strip.setPixelColorRGB(n=i, red=0, green=0, blue=0)
            time.sleep(0.01)
            self.led_strip.show()

    # main function to control the led hardware
    def update_led_strips(self, led_note_rows:list):
        if debug:
            print('Will now update the colors of the ledstrips')

        # reset the lists
        self.note_led_rows = led_note_rows
        self.all_colors_as_str = []
        self.all_led_rgb_value_lists = []

        self.set_led_colors()
        self.update_led_strip_colors()

        if debug:
            # print('note_led_rows: ', self.note_led_rows)
            # print('all_colors_as_str: ', self.all_colors_as_str)
            print('all_led_rgb_value_list: ', self.all_led_rgb_value_lists)

        self.display_updated_leds()
Beispiel #28
0
class LTSmart:

    mensaje = 'POSTE'
    contador_pantalla = -8
    contador_pantalla_max = 0
    contador_barra = 0

    def __init__(self, pin, channel, cintas, longitud, longitud_baliza):

        # ARREGLO LINEAL LED
        self.long_baliza = longitud_baliza
        self.Longitud = longitud  # Longitud de cada cinta Led
        self.Numero = cintas  # Numero de cintas Leds
        self.LED_COUNT = longitud * cintas + longitud_baliza  # Number of LED pixels.
        self.LED_PIN = pin  # GPIO pin connected to the pixels (must support PWM!).
        self.LED_FREQ_HZ = 800000  # LED signal frequency in hertz (usually 800khz)
        self.LED_DMA = 10  # DMA channel to use for generating signal (try 10)
        self.LED_BRIGHTNESS = 150  # Set to 0 for darkest and 255 for brightest
        self.LED_INVERT = False  # True to invert the signal (when using NPN transistor level shift)
        self.LED_CHANNEL = channel

        self.strip = Adafruit_NeoPixel(self.LED_COUNT, self.LED_PIN,
                                       self.LED_FREQ_HZ, self.LED_DMA,
                                       self.LED_INVERT, self.LED_BRIGHTNESS,
                                       self.LED_CHANNEL)
        self.strip.begin()

        self.ConvBin2 = [0, 0, 0, 0, 0, 0, 0, 0]  #Vector Conversor a Binario
        self.mensaje_anterior = 'POSTE'
        self.contador_dp = 0  # Contador para los dos puntos

    #---------------------------------------------------------------------------#
    #		Escribir pantalla													#
    #---------------------------------------------------------------------------#
    def screen(self, msg, Rojo, Verde, Azul, sentido, brillo, activar_barra,
               variable, lim_sup, lim_inf, n1, n2, n3):

        self.strip.setBrightness(brillo)
        self.mensaje = msg

        if self.mensaje_anterior != self.mensaje:
            self.contador_pantalla = -8

        self.CleanScreen(Color(0, 0, 0))

        if activar_barra == 0:
            # La barra está desactivada, muestra el texto completo en la pantalla
            if sentido == 0:
                # El texto se muestra estático
                self.contador_pantalla = self.Longitud - 10
                self.Message(self.mensaje, self.contador_pantalla,
                             Color(Verde, Rojo, Azul))
                self.strip.show()  # Mostrar el programa
            else:
                # El texto se desplaza hacia arriba
                self.contador_pantalla_max = len(
                    self.mensaje) * 8 + self.Longitud
                if self.contador_pantalla < len(
                        self.mensaje) * 8 + self.Longitud:
                    self.CleanScreen(Color(0, 0, 0))
                    self.Message(self.mensaje, self.contador_pantalla,
                                 Color(Verde, Rojo, Azul))
                    self.strip.show()  # Mostrar el programa
                else:
                    self.contador_pantalla = -8
        else:
            # La barra está activada, quita el último metro de la pantalla
            if sentido == 0:
                # El texto se muestra estático
                self.nivel(variable, lim_sup, lim_inf, n1, n2, n3)
                self.contador_pantalla = self.Longitud - 10 - 61
                self.Message(self.mensaje, self.contador_pantalla,
                             Color(Verde, Rojo, Azul))
                self.strip.show()  # Mostrar el programa
            else:
                # El texto se desplaza hacia arriba
                self.contador_pantalla_max = len(
                    self.mensaje) * 8 + self.Longitud - 50
                if self.contador_pantalla < len(
                        self.mensaje) * 8 + self.Longitud - 50:
                    self.CleanScreen(Color(0, 0, 0))
                    self.Message(self.mensaje, self.contador_pantalla,
                                 Color(Verde, Rojo, Azul))
                    self.CleanBarra(self.Longitud - 61, self.Longitud - 1)
                    self.nivel(variable, lim_sup, lim_inf, n1, n2, n3)
                    self.strip.show()  #Mostrar el programa
                else:
                    self.contador_pantalla = -8

        self.contador_pantalla += 1
        self.mensaje_anterior = self.mensaje

    #---------------------------------------------------------------------------#
    #		Apagar pantalla														#
    #---------------------------------------------------------------------------#
    def apagar(self):
        self.CleanAll(Color(0, 0, 0))
        self.strip.show()  # Mostrar el programa

    #---------------------------------------------------------------------------#
    #		Mostrar barra														#
    #---------------------------------------------------------------------------#
    def nivel(self, variable, lim_sup, lim_inf, n1, n2, n3):
        # self.CleanScreen(Color(0, 0, 0))
        j = self.Longitud - 60
        self.line(j, Color(255, 0, 255))
        j = self.Longitud - 59
        self.line(j, Color(255, 0, 255))
        j = self.Longitud - 3
        self.line(j, Color(255, 0, 255))
        j = self.Longitud - 2
        self.line(j, Color(255, 0, 255))

        led_nivel = int(round(variable * 56 / (lim_sup - lim_inf)))
        # print(led_nivel)
        grb = [0, 0, 0]

        for k in range(self.Longitud - 58, self.Longitud - 60 + led_nivel - 1):
            if variable < 1:
                grb = [0, 0, 0]
            elif variable < n1:
                grb = [255, 0, 0]
            elif variable < n2:
                grb = [255, 255, 0]
            elif variable < n3:
                grb = [100, 255, 0]
            else:
                grb = [0, 255, 0]

            self.line(k, Color(grb[0], grb[1], grb[2]))

        if self.contador_barra < k:
            self.contador_barra = k + 1
        elif self.contador_barra != k:
            self.contador_barra = self.contador_barra - 1

        self.line(self.contador_barra, Color(255, 255, 255))

    #---------------------------------------------------------------------------#
    #		Mostrar baliza														#
    #---------------------------------------------------------------------------#
    def nivel_baliza(self, variable, lim_sup, lim_inf, n1, n2, n3):
        grb = [0, 0, 0]
        if variable < 1:
            grb = [0, 0, 0]
        elif variable < n1:
            grb = [255, 0, 0]
        elif variable < n2:
            grb = [255, 255, 0]
        elif variable < n3:
            grb = [100, 255, 0]
        else:
            grb = [0, 255, 0]

        for k in range(self.LED_COUNT - self.long_baliza, self.LED_COUNT):
            self.strip.setPixelColor(k, Color(grb[0], grb[1], grb[2]))

    #---------------------------------------------------------------------------#
    #		Binario convertido a Leds	(Se usa en el medio)					#
    #---------------------------------------------------------------------------#
    def Bin2Led_medio(self, hexa, posicion, color, direccion):
        ConvBin = bin(hexa)
        if direccion == 0:
            for i in range(2, len(ConvBin)):
                if ConvBin[i] == '0':
                    self.strip.setPixelColor(posicion + len(ConvBin) - i,
                                             Color(0, 0, 0))
                else:
                    self.strip.setPixelColor(posicion + len(ConvBin) - i,
                                             color)
        else:
            for i in range(2, len(ConvBin)):
                if ConvBin[i] == '0':
                    self.strip.setPixelColor(posicion - len(ConvBin) + i,
                                             Color(0, 0, 0))
                else:
                    self.strip.setPixelColor(posicion - len(ConvBin) + i,
                                             color)

    #---------------------------------------------------------------------------#
    #		Binario convertido a Leds2	(Se usa en el borde superior)			#
    #---------------------------------------------------------------------------#
    def Bin2Led_superior(self, hexa, posicion, color, direccion, dif):
        ConvBin = bin(hexa)

        if len(ConvBin) != 10:
            self.ConvBin2 = ['0', '0', '0', '0', '0', '0', '0', '0']
            for j in range(2, len(ConvBin)):
                self.ConvBin2[10 - len(ConvBin) + j - 2] = ConvBin[j]
        else:
            for i in range(0, 7):
                self.ConvBin2[i] = ConvBin[i + 2]
        # Los leds en la misma dirección
        if direccion == 0:
            for i in range(0, dif):
                if self.ConvBin2[8 - dif + i] == '0':
                    self.strip.setPixelColor(posicion + dif - i,
                                             Color(0, 0, 0))
                else:
                    self.strip.setPixelColor(posicion + dif - i, color)
        # Los leds en dirección opuesta
        else:
            for i in range(0, dif):
                if self.ConvBin2[8 - dif + i] == '0':
                    self.strip.setPixelColor(posicion - dif + i,
                                             Color(0, 0, 0))
                else:
                    self.strip.setPixelColor(posicion - dif + i, color)

    #---------------------------------------------------------------------------#
    #		Binario convertido a Leds2	(Se usa en el borde inferior)			#
    #---------------------------------------------------------------------------#
    def Bin2Led_inferior(self, hexa, posicion, color, direccion, dif):
        ConvBin = bin(hexa)

        if len(ConvBin) != 10:
            self.ConvBin2 = ['0', '0', '0', '0', '0', '0', '0', '0']
            for j in range(2, len(ConvBin)):
                self.ConvBin2[10 - len(ConvBin) + j - 2] = ConvBin[j]
        else:
            for i in range(0, 7):
                self.ConvBin2[i] = ConvBin[i + 2]
        # Los leds en la misma dirección
        if direccion == 0:
            for i in range(0, dif):
                #print(8 - dif + i)
                if self.ConvBin2[i] == '0':
                    self.strip.setPixelColor(posicion + 8 - i, Color(0, 0, 0))
                else:
                    self.strip.setPixelColor(posicion + 8 - i, color)
        # Los leds en dirección opuesta
        else:
            for i in range(0, dif):
                if self.ConvBin2[i] == '0':
                    self.strip.setPixelColor(posicion - 8 + i, Color(0, 0, 0))
                else:
                    self.strip.setPixelColor(posicion - 8 + i, color)

    #---------------------------------------------------------------------------#
    #		Letras convertidas a Leds											#
    #---------------------------------------------------------------------------#
    def Letras2Led(self, posicion2, color, hexa):
        # Borde superior
        if posicion2 > self.Longitud - 9:
            dif = self.Longitud - 1 - posicion2
            if dif > 0:
                self.Bin2Led_superior(hexa[4], posicion2, color, 0, dif)
                self.Bin2Led_superior(hexa[3],
                                      2 * self.Longitud - posicion2 - 1, color,
                                      1, dif)
                self.Bin2Led_superior(hexa[2], 2 * self.Longitud + posicion2,
                                      color, 0, dif)
                self.Bin2Led_superior(hexa[1],
                                      4 * self.Longitud - posicion2 - 1, color,
                                      1, dif)
                self.Bin2Led_superior(hexa[0], 4 * self.Longitud + posicion2,
                                      color, 0, dif)
        # Borde inferior
        elif posicion2 < -1:
            dif2 = 9 - posicion2 * -1
            self.Bin2Led_inferior(hexa[4], posicion2, color, 0, dif2)
            self.Bin2Led_inferior(hexa[3], 2 * self.Longitud - posicion2 - 1,
                                  color, 1, dif2)
            self.Bin2Led_inferior(hexa[2], 2 * self.Longitud + posicion2,
                                  color, 0, dif2)
            self.Bin2Led_inferior(hexa[1], 4 * self.Longitud - posicion2 - 1,
                                  color, 1, dif2)
            self.Bin2Led_inferior(hexa[0], 4 * self.Longitud + posicion2,
                                  color, 0, dif2)

        # El centro de la pantalla
        else:
            self.Bin2Led_medio(hexa[4], posicion2, color, 0)
            self.Bin2Led_medio(hexa[3], 2 * self.Longitud - posicion2 - 1,
                               color, 1)
            self.Bin2Led_medio(hexa[2], 2 * self.Longitud + posicion2, color,
                               0)
            self.Bin2Led_medio(hexa[1], 4 * self.Longitud - posicion2 - 1,
                               color, 1)
            self.Bin2Led_medio(hexa[0], 4 * self.Longitud + posicion2, color,
                               0)

    #---------------------------------------------------------------------------#
    #		Limpiar pantalla													#
    #---------------------------------------------------------------------------#
    def CleanScreen(self, color):
        for i in range(self.LED_COUNT - self.long_baliza):
            self.strip.setPixelColor(i, color)

    #---------------------------------------------------------------------------#
    #		Limpiar pantalla y baliza											#
    #---------------------------------------------------------------------------#
    def CleanAll(self, color):
        for i in range(self.LED_COUNT):
            self.strip.setPixelColor(i, color)

    #---------------------------------------------------------------------------#
    #		Limpiar barra														#
    #---------------------------------------------------------------------------#
    def CleanBarra(self, j, k):
        for i in range(j, k):
            self.line(i, Color(0, 0, 0))

    #---------------------------------------------------------------------------#
    #		Dibujar una línea													#
    #---------------------------------------------------------------------------#
    def line(self, i, color):
        self.strip.setPixelColor(i, color)
        self.strip.setPixelColor((2 * self.Longitud - i) - 1, color)
        self.strip.setPixelColor(2 * self.Longitud + i, color)
        self.strip.setPixelColor((4 * self.Longitud - i) - 1, color)
        self.strip.setPixelColor(4 * self.Longitud + i, color)

    #---------------------------------------------------------------------------#
    #		Mensaje convertido a cada letra, numero o simbolo 					#
    #---------------------------------------------------------------------------#

    def tabla(self, valor, posicion3, color, i):

        switcher = {
            # MAYUSCULAS
            "A":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x3E, 0x48, 0x88, 0x48, 0x3E]),
            "B":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x6C, 0x92, 0x92, 0x92, 0xFE]),
            "C":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x44, 0x82, 0x82, 0x82, 0x7C]),
            "D":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x7C, 0x82, 0x82, 0x82, 0xFE]),
            "E":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x82, 0x92, 0x92, 0x92, 0xFE]),
            "F":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x80, 0x90, 0x90, 0x90, 0xFE]),
            "G":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0xCE, 0x8A, 0x82, 0x82, 0x7C]),
            "H":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0xFE, 0x10, 0x10, 0x10, 0xFE]),
            "I":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x00, 0x82, 0xFE, 0x82, 0x00]),
            "J":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x80, 0xFC, 0x82, 0x02, 0x04]),
            "K":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x82, 0x44, 0x28, 0x10, 0xFE]),
            "L":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x02, 0x02, 0x02, 0x02, 0xFE]),
            "M":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0xFE, 0x40, 0x38, 0x40, 0xFE]),
            "N":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0xFE, 0x08, 0x10, 0x20, 0xFE]),
            #"Ñ": lambda: self.Letras2Led(posicion3 - 8 * i, color, [0xBE,0x84,0x88,0x90,0xBE]),
            "O":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x7C, 0x82, 0x82, 0x82, 0x7C]),
            "P":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x60, 0x90, 0x90, 0x90, 0xFE]),
            "Q":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x7A, 0x84, 0x8A, 0x82, 0x7C]),
            "R":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x62, 0x94, 0x98, 0x90, 0xFE]),
            "S":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x4C, 0x92, 0x92, 0x92, 0x64]),
            "T":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0xC0, 0x80, 0xFE, 0x80, 0xC0]),
            "U":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0xFC, 0x02, 0x02, 0x02, 0xFC]),
            "V":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0xF8, 0x04, 0x02, 0x04, 0xF8]),
            "W":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0xFE, 0x02, 0x1C, 0x02, 0xFE]),
            "X":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0xC6, 0x28, 0x10, 0x28, 0xC6]),
            "Y":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0xC0, 0x20, 0x1E, 0x20, 0xC0]),
            "Z":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0xC2, 0xB2, 0x92, 0x9A, 0x86]),

            # MINUSCULAS
            "a":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x02, 0x1E, 0x2A, 0x2A, 0x04]),
            "b":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x1C, 0x22, 0x22, 0x14, 0xFE]),
            "c":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x14, 0x22, 0x22, 0x22, 0x1C]),
            "d":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0xFE, 0x14, 0x22, 0x22, 0x1C]),
            "e":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x18, 0x2A, 0x2A, 0x2A, 0x1C]),
            "f":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x40, 0x90, 0x7E, 0x10, 0x00]),
            "g":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x3C, 0x72, 0x4A, 0x4A, 0x30]),
            "h":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x1E, 0x20, 0x20, 0x10, 0xFE]),
            "i":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x00, 0x02, 0xBE, 0x22, 0x00]),
            "j":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x00, 0xBC, 0x02, 0x02, 0x04]),
            "k":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x00, 0x22, 0x14, 0x08, 0xFE]),
            "l":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x00, 0x02, 0xFE, 0x82, 0x00]),
            "m":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x3E, 0x20, 0x1E, 0x20, 0x3E]),
            "n":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x1E, 0x20, 0x20, 0x10, 0x3E]),
            "o":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x1C, 0x22, 0x22, 0x22, 0x1C]),
            "p":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x30, 0x48, 0x48, 0x30, 0x7E]),
            "q":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x7E, 0x30, 0x48, 0x48, 0x30]),
            "r":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x10, 0x20, 0x20, 0x10, 0x3E]),
            "s":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x24, 0x2A, 0x2A, 0x2A, 0x12]),
            "t":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x24, 0x12, 0xFC, 0x20, 0x20]),
            "u":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x3E, 0x04, 0x02, 0x02, 0x3C]),
            "v":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x38, 0x04, 0x02, 0x04, 0x38]),
            "w":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x3C, 0x02, 0x0C, 0x02, 0x3C]),
            "x":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x22, 0x14, 0x08, 0x14, 0x22]),
            "y":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x7C, 0x12, 0x12, 0x12, 0x64]),
            "z":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x22, 0x32, 0x2A, 0x26, 0x22]),

            # NUMEROS
            "0":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x7C, 0xA2, 0x92, 0x8A, 0x7C]),
            "1":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x00, 0x02, 0xFE, 0x42, 0x00]),
            "2":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x62, 0x92, 0x92, 0x92, 0x4E]),
            "3":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0xCC, 0xB2, 0x92, 0x82, 0x84]),
            "4":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x08, 0xFE, 0x48, 0x28, 0x18]),
            "5":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x9C, 0xA2, 0xA2, 0xA2, 0xE4]),
            "6":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x8C, 0x92, 0x92, 0x52, 0x3C]),
            "7":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0xE0, 0x90, 0x88, 0x84, 0x82]),
            "8":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x6C, 0x92, 0x92, 0x92, 0x6C]),
            "9":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x78, 0x94, 0x92, 0x92, 0x62]),

            # SIMBOLOS
            "=":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x28, 0x28, 0x28, 0x28, 0x28]),
            "(":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x00, 0x82, 0x44, 0x38, 0x00]),
            ")":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x00, 0x38, 0x44, 0x82, 0x00]),
            ":":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x00, 0x00, 0x28, 0x00, 0x00]),
            ";":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x00, 0x00, 0x2C, 0x02, 0x00]),
            " ":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x00, 0x00, 0x00, 0x00, 0x00]),
            ",":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x00, 0x00, 0x0C, 0x02, 0x00]),
            "?":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x60, 0x90, 0x9A, 0x80, 0x40]),
            ".":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x00, 0x0C, 0x0C, 0x00, 0x00]),
            "%":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x46, 0x26, 0x10, 0xC8, 0xC4]),
            "/":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x04, 0x08, 0x10, 0x20, 0x40]),
            "@":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x7E, 0x81, 0x8F, 0x89, 0x46]),  #Tipo 1
            #"@": lambda: self.Letras2Led(posicion3 - 8 * i, color, [0x72,0xB1,0xB1,0x81,0x7E]), # Tipo 2
            "*":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x00, 0x50, 0xE0, 0x50, 0x00]),  #Tipo 1
            #"*": lambda: self.Letras2Led(posicion3 - 8 * i, color, [0x14,0x08,0x3E,0x08,0x14]), # Tipo 2
            "$":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x44, 0x4A, 0xFF, 0x4A, 0x32]),
            "!":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x00, 0x00, 0xFA, 0x00, 0x00]),
            "#":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x44, 0xFF, 0x44, 0xFF, 0x44]),
            "+":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x10, 0x10, 0x7C, 0x10, 0x10]),
            "-":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x00, 0x10, 0x10, 0x10, 0x00]),
            "_":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x01, 0x01, 0x01, 0x01, 0x01]),

            # ESPECIALES

            # Unidades
            "\x80":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x22, 0x41, 0x22, 0xDC, 0xC0]),  # °C
            "\x81":
            lambda: self.Letras2Led(posicion3 - 8 * i, color, [
                0x00, 0x00, 0x00, 0xC0, 0xC0
            ]),  # ° pequeño
            "\x82":
            lambda: self.Letras2Led(posicion3 - 8 * i, color, [
                0x00, 0x00, 0xE0, 0xA0, 0xE0
            ]),  # ° grande
            "\x83":
            lambda: self.Letras2Led(posicion3 - 8 * i, color, [
                0x78, 0x04, 0x04, 0x7F, 0x00
            ]),  # u letra griega

            # Simbolos
            "\x84":
            lambda: self.Letras2Led(posicion3 - 8 * i, color, [
                0x00, 0x00, 0x10, 0x00, 0x00
            ]),  # Punto centro Pequeño
            "\x85":
            lambda: self.Letras2Led(posicion3 - 8 * i, color, [
                0x00, 0x1C, 0x1C, 0x1C, 0x00
            ]),  # Punto centro Grande

            # Iconos
            "\x86":
            lambda: self.Letras2Led(posicion3 - 8 * i, color, [
                0x30, 0x78, 0x3C, 0x78, 0x30
            ]),  # Corazón relleno
            "\x87":
            lambda: self.Letras2Led(posicion3 - 8 * i, color, [
                0x30, 0x48, 0x24, 0x48, 0x30
            ]),  # Corazón blanco
            "\x88":
            lambda: self.Letras2Led(posicion3 - 8 * i, color, [
                0x38, 0xE4, 0x27, 0xE4, 0x38
            ]),  # Conector
            "\x89":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x00, 0x00, 0xFF, 0x00, 0x00]),  # Cable	
            "\x90":
            lambda: self.Letras2Led(posicion3 - 8 * i, color, [
                0xFC, 0x4C, 0x20, 0x1F, 0x03
            ]),  # Nota musical
            "\x91":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0xFF, 0x4F, 0x4F, 0x4F, 0x7F]),  # Celular
            "\x92":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x08, 0x78, 0xFA, 0x78, 0x08]),  # Campana
            "\x93":
            lambda: self.Letras2Led(posicion3 - 8 * i, color, [
                0x08, 0x44, 0x14, 0x44, 0x08
            ]),  # Cara feliz

            #Animaciones
            "\x94":
            lambda: self.Letras2Led(posicion3 - 8 * i, color, [
                0x7C, 0x3E, 0x1E, 0x3E, 0x7C
            ]),  # Pacman abierto
            "\x95":
            lambda: self.Letras2Led(posicion3 - 8 * i, color, [
                0x7C, 0xFE, 0xFE, 0xFE, 0x7C
            ]),  # Pacman cerrado
            "\x96":
            lambda: self.Letras2Led(posicion3 - 8 * i, color,
                                    [0x7C, 0xCF, 0xFE, 0xCF, 0x7C]),  # Fantom1
            "\x97":
            lambda: self.Letras2Led(posicion3 - 8 * i, color, [
                0x7F, 0xCC, 0xFF, 0xCC, 0x7F
            ]),  # Fantom2		
        }.get(valor, lambda: None)()

    def Message(self, mensaje, posicion3, color):
        for i in range(len(mensaje)):

            self.tabla(mensaje[i], posicion3, color, i)

    #---------------------------------------------------------------------------#
    #		Reiniciar contador de Pantalla 		 								#
    #---------------------------------------------------------------------------#

    def reiniciar(self):
        self.contador_pantalla = -8
Beispiel #29
0
class GpioThread(threading.Thread):

    KEYWORDS = [
        "help", "module", "filter", "transition", "update", "off", "?", "h",
        "m", "f", "t", "u"
    ]

    def __init__(self):
        threading.Thread.__init__(self)

        self.strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ,
                                       LED_DMA, LED_INVERT, LED_BRIGHTNESS)
        self.strip.begin()

        self.exit = False
        self.command = None
        self.reply = None
        self.lock = threading.Condition()

        self.isConnected = False
        self.isConnectedTick = 0

        self.commandId = 0
        logging.info("GpioThread initialized")

    def run(self):

        # self.moduleFactory = DefaultComponents.ColorModule
        self.moduleFactory = Cannon.Cannon
        self.filterFactory = DefaultComponents.NoneFilter
        self.transitionFactory = DefaultComponents.NoneTransition

        self.moduleFactory.configure([])
        self.filterFactory.configure([])
        self.transitionFactory.configure([])

        self.module = self.filterFactory.getinstance(
            self.moduleFactory.getinstance())

        logging.debug("GpioThread started (Thread name={})".format(
            threading.Thread.getName(self)))

        messageNumber = 0

        while True:
            self.lock.acquire()
            if self.exit:
                self.lock.release()
                break

            if self.command is not None:
                messageNumber += 1
                logging.debug("Received message #{}: {}".format(
                    messageNumber, self.command))
                self.reply = self.processCommandT(self.command)
                self.command = None
                # self.lock.notify()
                logging.debug("Notified message #{}: {}".format(
                    messageNumber, self.reply))

            self.lock.release()

            block = self.module.next()

            self.isConnectedTick += 1
            if self.isConnectedTick >= 100:
                if not self.isConnected:
                    block[0] = [255, 0, 0]
                    block[1] = [0, 0, 0]
                self.isConnectedTick = 0
            self.project(block)

        logging.info("GpioThread stopping")

        for i in range(LED_COUNT):
            self.strip.setPixelColor(i, 0x0)
        self.strip.show()

    def processCommandT(self, line):
        """Apply the changes, ane return the reply to the command"""
        chunks = line.split()
        if len(chunks) <= 0:
            return "ERR: Empty command"
        if not chunks[0] in GpioThread.KEYWORDS:
            return "ERR: Unknown keyword {}; use \"help\" or \"?\" for references"

        if chunks[0] in ["help", "h", "?"]:
            if len(chunks) == 1:
                return self.getHelp()
            return self.getHelp(chunks[1:])

        if chunks[0] in ["update", "u"]:
            self.update(
                self.filterFactory.getinstance(
                    self.moduleFactory.getinstance()))
            return "OK: Transition complete"

        if chunks[0] in ["module", "m"]:
            if len(chunks) < 2:
                return self.getHelp(["m"])
            module = Defs.MODULES.get(chunks[1])
            if module is None:
                return "ERR: unknown module \"{}\"".format(chunks[1])
            self.moduleFactory = module
            self.moduleFactory.configure(chunks[2:])
            return "OK: Module set to \"{}\"; use >> update << to apply changes".format(
                chunks[1])

        if chunks[0] in ["filter", "f"]:
            if len(chunks) < 2:
                return self.getHelp(["f"])
            factory = Defs.FILTERS.get(chunks[1])
            if factory is None:
                return "ERR: unknown filter \"{}\"".format(chunks[1])
            self.filterFactory = factory
            self.filterFactory.configure(chunks[2:])
            return "OK: Filter set to \"{}\"; use >> update << to apply changes".format(
                chunks[1])

        if chunks[0] in ["transition", "t"]:
            if len(chunks) < 2:
                return self.getHelp(["t"])
            transition = Defs.TRANSITIONS.get(chunks[1])
            if transition is None:
                return "ERR: unknown transition \"{}\"".format(chunks[1])
            self.transitionFactory = transition
            self.transitionFactory.configure(chunks[2:])
            return "OK: Transition set to \"{}\"; use >> update << to apply changes".format(
                chunks[1])

        if chunks[0] in ["off"]:
            Defs.MODULES.get("color").configure(["0x0"])
            self.update(Defs.MODULES.get("color").getinstance())
            # no filter used
            return "Strand off"

        return "TODO: Process commands"

    def update(self, afterModule):
        logging.info("Starting transition")
        transition = self.transitionFactory.newinstance(
            self.module, afterModule)
        block = transition.next()
        while block is not None:
            self.project(block)
            block = transition.next()
        self.module = afterModule
        logging.info("Transition finished")

    def getHelp(self, topic=[]):
        if len(topic) > 0:
            if topic[0] in ["module", "m"]:
                if len(topic) > 1:
                    name = topic[1]
                    if name in Defs.MODULES.keys():
                        module = Defs.MODULES[name]
                        return Const.APP_NAME + " \"{}\":\n{}".format(
                            module.name, module.help)
                    return Const.APP_NAME + " modules: Unknown name \"{}\"".format(
                        name)
                return Const.APP_NAME + " modules: {}".format(
                    Defs.MODULES.keys())

            if topic[0] in ["filter", "f"]:
                if len(topic) > 1:
                    name = topic[1]
                    if name in Defs.FILTERS.keys():
                        filter = Defs.FILTERS[name]
                        return Const.APP_NAME + " \"{}\":\n{}".format(
                            filter.name, filter.help)
                    return Const.APP_NAME + " filters: Unknown name \"{}\"".format(
                        name)
                return Const.APP_NAME + " filters: {}\n".format(
                    Defs.FILTERS.keys())

            if topic[0] in ["transition", "t"]:
                if len(topic) > 1:
                    name = topic[1]
                    if name in Defs.TRANSITIONS.keys():
                        transition = Defs.TRANSITIONS[name]
                        return Const.APP_NAME + " \"{}\":\n{}".format(
                            transition.name, transition.help)
                    return Const.APP_NAME + " transitions: Unknown name \"{}\"".format(
                        name)
                return Const.APP_NAME + " transitions: {}\n".format(
                    Defs.TRANSITIONS.keys())

        return Const.APP_NAME + " manual. The recognized keywords are\n" \
               "  module/m: graphics painter configuration\n" \
               "  filter/f: display filter configuration; filters are used to display only subsections of the graphics\n" \
               "  transition/t: configure transition used to update to new graphics module or filter\n" \
               "  update/u: execute the configuration changes\n" \
               "  off: turn the strand off (display black)\n" \
               "  help/h/?: display help. use >> help <keyword> << to list available configuration details\n"

    def ctrl(self, command):
        self.lock.acquire()
        self.command = command
        self.commandId += 1
        logging.debug("Setting command #{}: {}".format(self.commandId,
                                                       command))
        self.reply = None

        boo = self.lock.wait(1)
        if not boo:
            logging.warning("Condition timed out. Command={}".format(
                self.command))

        reply = self.reply
        if reply == None:
            logging.warning("Command \"{}\": no reply set!")
            reply = "ERR: no reply received"

        self.lock.release()
        return reply

    def quit(self):
        self.lock.acquire()
        self.exit = True
        logging.info("GpioThread signalled to stop")
        self.lock.release()

    def __adjust(self, num):
        return num * (num >> 2) >> 6
        # return num

    def __toGrbInt(self, tuple):
        ret = (self.__adjust(tuple[1]) << 16) \
              + (self.__adjust(tuple[0]) << 8) \
              + self.__adjust(tuple[2])
        return ret

    def project(self, block):
        # print("Graphics colors={}"
        #       .format(map(hex, map(lambda x: (x[0] << 16) + (x[1] << 8) + x[2], block))))
        for i in range(LED_COUNT):
            self.strip.setPixelColor(i, self.__toGrbInt(block[i]))
        self.strip.show()
Beispiel #30
0
        for i, pos in enumerate(self.snake):
            _set_pixel(strip, pos, Color(255 - (snake_len - i) * 20, 0, 0))
        if self.to_clear:
            _set_pixel(strip, self.to_clear, Color(0, 0, 0))
        if self.reward:
            _set_pixel(strip, self.reward, REWARD_COLORS[self._frame % len(REWARD_COLORS)])


if __name__ == '__main__':
    stdscr = curses.initscr()
    curses.cbreak()
    stdscr.keypad(1)
    stdscr.nodelay(1)

    # Create NeoPixel object with appropriate configuration.
    strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS)
    strip.begin()

    try:
        while True:
            game = Game()
            while game.is_on:
                game.input(stdscr.getch())
                game.next_frame()
                game.draw(strip)
                strip.show()
                time.sleep(0.15)
            clrscr(strip)
    except KeyboardInterrupt:
        curses.endwin()
class Controller:

    LEDS = None

    NEOPIXEL_GPIO_PIN = None
    NEOPIXEL_FREQUENCY = None
    NEOPIXEL_DMA = None
    NEOPIXEL_INVERT = None
    NEOPIXEL_BRIGHTNESS = None
    NEOPIXEL_CHANNEL = None
    NEOPIXEL_STRIP = None

    neopixel = None

    thread = None

    effect = None

    def __init__(self, leds, neopixel_gpio_pin, neopixel_frequency, neopixel_dma, neopixel_invert, neopixel_brightness, neopixel_channel, neopixel_strip):
        print("[Neopixel][info] Initialising NeoPixel")

        self.LEDS = leds
        self.NEOPIXEL_GPIO_PIN = neopixel_gpio_pin
        self.NEOPIXEL_FREQUENCY = neopixel_frequency
        self.NEOPIXEL_DMA = neopixel_dma
        self.NEOPIXEL_INVERT = neopixel_invert
        self.NEOPIXEL_BRIGHTNESS = neopixel_brightness
        self.NEOPIXEL_CHANNEL = neopixel_channel
        self.NEOPIXEL_STRIP = neopixel_strip

        self.neopixel = Adafruit_Neopixel(
            self.LEDS,
            self.NEOPIXEL_GPIO_PIN,
            self.NEOPIXEL_FREQUENCY,
            self.NEOPIXEL_DMA,
            self.NEOPIXEL_INVERT,
            self.NEOPIXEL_BRIGHTNESS,
            self.NEOPIXEL_CHANNEL,
            self.NEOPIXEL_STRIP
        )

        try:
            self.neopixel.begin()
        except AttributeError:
            print("[Neopixel][error] An error occurred initialising NeoPixel")

    def pixel_color(self, pixel, color):
        print("[Controller][info] Setting color: '%s' to NeoPixel pixel '%d'" % (color.get_hex(), pixel))

        try:
            self.neopixel.setPixelColor(pixel, color.get_bit())
            self.neopixel.show()
        except AttributeError:
            print("[Controller][error] An error occurred setting color to NeoPixel pixel")

    def color_wheel(self, pos):
        print("[Controller][info] Generation a color wheel")

        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 brightness(self, brightness):
        print("[Controller][info] Setting brightness: '%d' to NeoPixel pixels" % (brightness))

        try:
            self.neopixel.setBrightness(brightness)
            self.neopixel.show()
        except AttributeError:
            print("[Neopixel][error] An error occurred setting brightness on NeoPixel")

    def color(self, color):
        print("[Controller][info] Setting color: '%s' to NeoPixel pixels" % (color.get_hex()))

        try:
            for i in range(self.LEDS):
                self.pixel_color(i, color)

            self.neopixel.show()
        except AttributeError:
            print("[Controller][error] An error occurred setting color to NeoPixel pixels")

    def start_effect(self, effect, color):
        print("[Controller][info] Starting effect: '%s' to NeoPixel pixels" % (effect))

        try:
            self.effect = eval(effect + '.' + effect.replace('_', ' ').title().replace(' ', ''))(self)

            self.thread = threading.Thread(target=self.effect.run, args=(color,))
            self.thread.daemon = True
            self.thread.start()
        except AttributeError:
            print("[Controller][error] An error occurred starting effect to NeoPixel pixels")

    def stop_effect(self):
        print("[Controller][info] Stopping effect to NeoPixel pixels")

        try:
            if self.effect is not None:
                self.effect.stop()
        except AttributeError:
            print("[Controller][error] An error occurred stopping effect to NeoPixel pixels")

    def quit_effect(self):
        print("[Controller][info] Quitting effect to NeoPixel pixels")

        try:
            if self.effect is not None:
                self.thread.terminate()
        except AttributeError:
            print("[Controller][error] An error occurred quitting effect to NeoPixel pixels")

    def effects(self):
        print("[Controller][info] Getting a list of NeoPixel effects")

        try:
            effects = [file for file in os.listdir('./neopixelcontroller/lib/effects') if not file.startswith('.') and not file.startswith('__init__') and not file.endswith('.pyc') and not file.startswith('effect_test')]

            return [effect.replace('.py', '') for effect in effects]
        except AttributeError:
            print("[Controller][error] An error occurred get NeoPixel effects")

    def clear(self):
        print("[Controller][info] Clearing pixels on NeoPixel")

        try:
            self.stop_effect()
            self.quit_effect()
            self.color(Color(0, 0, 0))
            self.brightness(0)
        except AttributeError:
            print("[Controller][error] An error occurred clearing all pixels on NeoPixel")

    def cleanup(self):
        print("[Controller][info] NeoPixel clean up")

        self.clear()

    def __exit__(self):
        print("[Controller][info] NeoPixel exit")

        self.cleanup()
Beispiel #32
0
class ColoramaDisplay(ApplicationSession):

    @inlineCallbacks
    def onJoin(self, details):

        self._serial = get_serial()
        self._prefix = u'io.crossbar.demo.iotstarterkit.{}.pixelstrip'.format(self._serial)

        self.log.info("Crossbar.io IoT Starterkit Serial No.: {serial}", serial=self._serial)
        self.log.info("ColoramaDisplay connected: {details}", details=details)

        # get custom configuration
        cfg = self.config.extra

        self._leds = Adafruit_NeoPixel(
            cfg['led_count'],
            cfg['led_pin'],
            cfg['led_freq_hz'],
            cfg['led_dma'],
            cfg['led_invert'],
            cfg['led_brightness'])

        self._leds.begin()

        for proc in [
            (self.set_color, 'set_color'),
            (self.get_color, 'get_color'),
            (self.flash, 'flash'),
            (self.lightshow, 'lightshow'),
            (self.color_wipe, 'color_wipe'),
            (self.theater_chase, 'theater_chase'),
            (self.rainbow, 'rainbow'),
            (self.rainbow_cycle, 'rainbow_cycle'),
            (self.theater_chaserainbow, 'theater_chaserainbow'),

        ]:
            yield self.register(proc[0], u'{}.{}'.format(self._prefix, proc[1]))

        self.flash()

        self.log.info("ColoramaDisplay ready!")

    @inlineCallbacks
    def flash(self, delay=50, repeat=5):
        delay = float(delay) / 1000.
        for i in range(repeat):
            self.set_color(0xe1, 0xda, 0x05)
            yield sleep(2 * delay)
            self.set_color(0x52, 0x42, 0x00)
            yield sleep(delay)

    @inlineCallbacks
    def lightshow(self):
        # Color wipe animations.
        yield self.color_wipe(255, 0, 0)  # Red wipe
        yield self.color_wipe(0, 255, 0)  # Blue wipe
        yield self.color_wipe(0, 0, 255)  # Green wipe
        # Theater chase animations.
        yield self.theater_chase(127, 127, 127)  # White theater chase
        yield self.theater_chase(127,   0,   0)  # Red theater chase
        yield self.theater_chase(0,   0, 127)  # Blue theater chase
        # Rainbow animations.
        yield self.rainbow()
        yield self.rainbow_cycle()
        #yield self.theater_chase_rainbow()
        yield self.flash()

    # Define functions which animate LEDs in various ways.
    @inlineCallbacks
    def color_wipe(self, r, g, b, wait_ms=50):
        """Wipe color across display a pixel at a time."""
        for i in range(self._leds.numPixels()):
            self.set_color(r, g, b, i)
            yield sleep(wait_ms / 1000.0)

    @inlineCallbacks
    def theater_chase(self, r, g, b, wait_ms=50, iterations=10):
        """Movie theater light style chaser animation."""
        for j in range(iterations):
            for q in range(3):
                for i in range(0, self._leds.numPixels(), 3):
                    self.set_color(r, g, b, i + q)
                yield sleep(wait_ms / 1000.0)
                for i in range(0, self._leds.numPixels(), 3):
                    self.set_color(0, 0, 0, i + q)

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

    @inlineCallbacks
    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._leds.numPixels()):
                r, g, b = self.wheel((i + j) & 255)
                self.set_color(r, g, b, i)
            yield sleep(wait_ms / 1000.0)

    @inlineCallbacks
    def rainbow_cycle(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._leds.numPixels()):
                r, g, b = self.wheel(((i * 256 / self._leds.numPixels()) + j) & 255)
                self.set_color(r, g, b, i)
            yield sleep(wait_ms / 1000.0)

    @inlineCallbacks
    def theater_chaserainbow(self, wait_ms=50):
        """Rainbow movie theater light style chaser animation."""
        for j in range(256):
            for q in range(3):
                for i in range(0, self._leds.numPixels(), 3):
                    r, g, b = self.wheel((i+j) % 255)
                    self.set_color(r, g, b, i + q)
                yield sleep(wait_ms / 1000.0)
                for i in range(0, self._leds.numPixels(), 3):
                    self.set_color(0, 0, 0, i)

    def set_color(self, red, green, blue, k=None):
        if k is None:
            for i in range(self._leds.numPixels()):
                # FIXME: not sure, but we need to swap this here. maybe it is the specific neopixels?
                self._leds.setPixelColorRGB(i, green, red, blue)
                color_change = {
                    u'led': i,
                    u'r': red,
                    u'g': green,
                    u'b': blue
                }
                self.publish(u'{}.on_color_set'.format(self._prefix), color_change)
        else:
                # FIXME: not sure, but we need to swap this here. maybe it is the specific neopixels?
            self._leds.setPixelColorRGB(k, green, red, blue)
            color_change = {
                u'led': k,
                u'r': red,
                u'g': green,
                u'b': blue
            }
            self.publish(u'{}.on_color_set'.format(self._prefix), color_change)
        self._leds.show()

    def get_color(self, k):
        c = self._leds.getPixelColor(k)
        color = {
            u'g': c >> 16,
            u'r': (c >> 8) & 0xff,
            u'b': c & 0xff,
        }
        return color

    def onLeave(self, details):
        self.log.info("Session closed: {details}", details=details)
        self.disconnect()

    def onDisconnect(self):
        self.log.info("Connection closed")
        for i in range(self._leds.numPixels()):
            self._leds.setPixelColorRGB(i, 0, 0, 0)
        self._leds.show()
        try:
            reactor.stop()
        except ReactorNotRunning:
            pass
Beispiel #33
0
class BinaryClock:

    '''
    The class, which makes the binary clock run...
    '''

    def __init__(self):

        GPIO.setmode(GPIO.BOARD)

        # absolute path to current file old: os.getcwd()
        self.basePath = os.path.dirname(
            os.path.abspath(
                inspect.getfile(
                    inspect.currentframe()
                )
            )
        )
        # Number of columns in clock
        self.clock_width = 6
        # Number of rows in clock
        self.clock_height = 4

        self.curr_fg_color = Color(0, 0, 0)
        self.curr_bg_color = Color(0, 0, 0)
        self.flag_clockIndent = False

        # Number of LED pixels.
        LED_COUNT = self.clock_width * self.clock_height
        # GPIO pin connected to the pixels (18 uses PWM!).
        LED_PIN = 18
        # LED signal frequency in hertz (usually 800khz)
        LED_FREQ_HZ = 800000
        # DMA channel to use for generating signal (try 5)
        LED_DMA = 5
        # Set to 0 for darkest and 255 for brightest
        LED_BRIGHTNESS = 128
        # True to invert the signal (when using NPN transistor level shift)
        LED_INVERT = False
        # set to '1' for GPIOs 13, 19, 41, 45 or 53
        LED_CHANNEL = 0
        # Strip type and colour ordering
        LED_STRIP = ws.WS2811_STRIP_GRB

        # path to configuration file
        cfgFilePath = os.path.join(self.basePath, 'config', 'clockConfig.cfg')
        if not os.path.exists(cfgFilePath):
            cfgFilePathDefault = os.path.join(self.basePath,
                                              'config',
                                              'clockConfig_default.cfg')
            copyfile(cfgFilePathDefault, cfgFilePath)

        # configuration setup
        self.configuration = bcc.ConfigFile(cfgFilePath)
        self.configuration.readConfigFile()

        self.helpers = bch.Helpers(self.configuration)

        # Create NeoPixel object with appropriate configuration.
        self.strip = Adafruit_NeoPixel(LED_COUNT,
                                       LED_PIN,
                                       LED_FREQ_HZ,
                                       LED_DMA,
                                       LED_INVERT,
                                       LED_BRIGHTNESS,
                                       LED_CHANNEL,
                                       LED_STRIP)

        # Intialize the library (must be called once before other functions).
        self.strip.begin()

        # LED Functions
        self.stripFunctions = bcl.LEDFunctions(self.strip,
                                               self.clock_width,
                                               self.clock_height)

        # Plugins
        self.plugin2 = p_TimeAsText.ShowTimeAsText(self.strip,
                                                   self.clock_width,
                                                   self.clock_height,
                                                   self.basePath)

        self.plugin3 = p_MatrixEffect.ShowMatrixEffect(self.strip,
                                                       self.clock_width,
                                                       self.clock_height,
                                                       self.configuration)

        self.plugin4 = p_SplashScreen.ShowSplashScreen(self.strip,
                                                       self.clock_width,
                                                       self.clock_height)

        self.plugin5 = p_RainbowAllLEDs.ShowRainbowAllLEDs(self.strip,
                                                           self.configuration)

        self.plugin6 = p_Fire.ShowFire(self.strip,
                                       self.clock_width,
                                       self.clock_height,
                                       self.configuration)

        # initialize the observer event
        watchedDir = os.path.join(self.basePath, 'config')
        self.event_handler = PatternMatchingEventHandler(
            patterns=["*.cfg"],
            ignore_patterns=[],
            ignore_directories=True)
        self.event_handler.on_any_event = self.on_any_event
        self.observer = Observer()
        self.observer.schedule(self.event_handler, watchedDir, recursive=False)
        self.observer.start()

        # ldr gpio pin number
        self.pin_to_circuit = 7
        self.brightness = self.configuration.brightness_general
        self.arr_ldrValues = []

    '''-------------------------------------------------------------------------
    # O T H E R   F U N C T I O N S ----------------------------------------'''

    def rc_time(self):

        while True:

            if self.configuration.running == self.configuration.stop == 1:
                break

            if self.configuration.sensitive == 1:

                GPIO.setup(self.pin_to_circuit, GPIO.OUT)
                GPIO.output(self.pin_to_circuit, GPIO.LOW)

                time.sleep(0.1)

                GPIO.setup(self.pin_to_circuit, GPIO.IN)

                c = 0
                while (GPIO.input(self.pin_to_circuit) == GPIO.LOW):
                    c += 1
                    if c >= 20000:
                        break

                self.arr_ldrValues.append(c)
                # print "c: " + str(c)

                if len(self.arr_ldrValues) == 10:
                    ldrValue = (sum(self.arr_ldrValues) - max(self.arr_ldrValues) -
                                min(self.arr_ldrValues)) / (len(self.arr_ldrValues) - 2)
                    del self.arr_ldrValues[:]

                    self.brightness = int(math.floor(
                        (238 / (1 + math.exp(0.000475 * (2.25 * ldrValue - 10000)))) + 19))
                    print str(self.brightness)

            else:

                self.brightness = self.configuration.brightness_general
                print str(self.brightness)
                time.sleep(0.5)

    # --------------------------------------------------------------------------

    def on_any_event(self, event):
        self.configuration.readConfigFile()
        if self.configuration.flag_whipeLEDs:
            self.stripFunctions.wipeLEDs()

    # --------------------------------------------------------------------------

    def upInTheSky(self):

        backgroundNoSeconds = [1, 2, 3, 4,
                               7, 8, 9, 10,
                               13, 14, 15, 16,
                               19, 20, 21, 22]

        arr = []
        # get current xy coordinates of lit LEDs
        for i in range(self.strip.numPixels()):
            if self.strip.getPixelColor(i) == self.curr_fg_color:
                arr.append(i)

        for j in range(4):
            for i, p in enumerate(arr):
                x, y = self.stripFunctions.get2DCoordinateFrom1D(p)
                self.stripFunctions.setColorBy2DCoordinates(x,
                                                            y - j,
                                                            self.curr_fg_color)
            self.strip.show()
            time.sleep(0.2)
            if self.configuration.show_seconds == 1:
                for i in range(self.strip.numPixels()):
                    self.stripFunctions.setColorBy1DCoordinate(
                        i,
                        self.curr_bg_color,
                        flag_forClock=self.flag_clockIndent)
            else:
                for i in range(len(backgroundNoSeconds)):
                    self.stripFunctions.setColorBy1DCoordinate(
                        backgroundNoSeconds[i],
                        self.curr_bg_color,
                        flag_forClock=self.flag_clockIndent)

        self.strip.show()
        time.sleep(1)

    '''-------------------------------------------------------------------------
    # B I N A R Y   C L O C K   F U N C T I O N S --------------------------'''

    def runClockBinary(self):

        while True:

            # get current time from system
            now = datetime.datetime.now()

            # get current minute and second Value for color within hour
            currTimeValue = now.second + (now.minute * 60)

            # 3600 iterations per hour over Rainbow colors
            for j in range(currTimeValue, 3600):

                if self.configuration.running == self.configuration.stop == 1:

                    # closing animtion
                    self.upInTheSky()
                    self.stripFunctions.wipeLEDs(Color(0, 0, 0))
                    self.configuration.saveConfigFile()
                    return

                # check if plugin should run
                if self.configuration.plugin != 1:
                    return

                # every hue devided into 3600 steps
                h = j / 3600.0

                self.binaryTime(h)

                # sleep for 1 second
                time.sleep(1)

    # --------------------------------------------------------------------------

    def binaryTime(self, hue):

        # foreground color
        colorForeground = self.helpers.getRainbowColor(
            self.configuration.rainbow,
            hue)

        self.curr_fg_color = colorForeground

        backgroundNoSeconds = [1, 2, 3, 4,
                               7, 8, 9, 10,
                               13, 14, 15, 16,
                               19, 20, 21, 22]

        # set background color
        if self.configuration.background == 1:
            colorBackground = Color(self.configuration.background_value,
                                    self.configuration.background_value,
                                    self.configuration.background_value)
        else:
            colorBackground = Color(0, 0, 0)

        self.curr_bg_color = colorBackground

        # show / hide seconds
        if self.configuration.show_seconds == 1:
            for i in range(self.strip.numPixels()):
                self.stripFunctions.setColorBy1DCoordinate(
                    i,
                    colorBackground,
                    flag_forClock=self.flag_clockIndent)
        else:
            for i in range(len(backgroundNoSeconds)):
                self.stripFunctions.setColorBy1DCoordinate(
                    backgroundNoSeconds[i],
                    colorBackground,
                    flag_forClock=self.flag_clockIndent)

        # get current Time
        curTime = datetime.datetime.now()

        # separate date elements
        year = curTime.year
        month = curTime.month
        day = curTime.day

        # separate time elements
        hour = curTime.hour
        minute = curTime.minute
        second = curTime.second

        # new year countdown
        if day == 31 and month == 12 and hour == 23 and minute == 59 and second = 50:
            open(os.path.join(self.basePath, 'other', 'customText.txt'), 'w').close()
            with open(os.path.join(self.basePath, 'other', 'customText.txt'), "a") as myfile:
                myfile.write("10 9 8 7 6 5 4 3 2 1 0 Frohes Neues Jahr " + str(year + 1))
            self.plugin2.showTimeAsText(fg_color=self.curr_fg_color,
                                        bg_color=self.curr_bg_color,
                                        fps=10)
        # ldr log file
        if hour == 0 and minute == 0 and second == 0:
            open(os.path.join(self.basePath, 'config', 'ldrValues.log'), 'w').close()

        if second == 0:
            with open(os.path.join(self.basePath, 'config', 'ldrValues.log'), "a") as myfile:
                myfile.write(str(hour) + ":" + str(minute) +
                             "  -  " + str(self.brightness) + "\n")

        print(str(hour) + ":" + str(minute) + ":" + str(second))

        # column values for hour, minues and seconds
        # if seconds should not be shown, hour and minute columns += 1
        y_posH = 0 if self.configuration.show_seconds == 1 else 1
        y_posM = 2 if self.configuration.show_seconds == 1 else 3
        y_posS = 4

        # hour
        self.columnValuesWithPixel(hour, y_posH, colorForeground)
        # minute
        self.columnValuesWithPixel(minute, y_posM, colorForeground)
        # second
        if self.configuration.show_seconds == 1:
            self.columnValuesWithPixel(second, y_posS, colorForeground)

        self.strip.setBrightness(self.brightness)

        self.strip.show()
Beispiel #34
0
class WPad(ApplicationSession):
    """
    Connects the Pi's GPIOs to WAMP.
    """
    PINMODES = {'bcm': GPIO.BCM, 'board': GPIO.BOARD}

    def _select_row(self, row=None):
        i = 0
        for pin in self._row_pins:
            if row is None or row != i:
                GPIO.output(pin, GPIO.HIGH)
            else:
                GPIO.output(pin, GPIO.LOW)
            i += 1

    def set_color(self, red, green, blue, k=None):
        if k is None:
            for i in range(self._ledstrip.numPixels()):
                self._ledstrip.setPixelColorRGB(i, green, red, blue)
        else:
            self._ledstrip.setPixelColorRGB(k, green, red, blue)
        self._ledstrip.show()

    @inlineCallbacks
    def flash(self, r=255, g=255, b=255, delay=25, repeat=10):
        delay = float(delay) / 1000.
        for i in range(repeat):
            self.set_color(r, g, b)
            yield sleep(2 * delay)
            self.set_color(0, 0, 0)
            yield sleep(delay)

    @inlineCallbacks
    def _tick(self):
        self._tick_no += 1
        now = time.time()
        self._tick_sent[self._tick_no] = now
        try:
            pub = yield self.publish(u'{}.on_alive'.format(self._prefix),
                                     self._tick_no,
                                     options=PublishOptions(acknowledge=True,
                                                            exclude_me=False))
        except:
            self.log.failure()
        else:
            self.log.info('TICK sent [tick {}, pub {}]'.format(
                self._tick_no, pub.id))

    def show_load(self):
        cpu_load = int(round(psutil.cpu_percent(interval=None)))
        mem_load = int(round(psutil.virtual_memory().percent))
        if cpu_load > 99:
            cpu_load = 99
        if mem_load > 99:
            mem_load = 99

        self._cpu_load.popleft()
        self._cpu_load.append(cpu_load)

        if not self._is_scrolling:
            text = "{:0>2d}{:0>2d}".format(mem_load, cpu_load)
            self._disp.setMessage(text)

    @inlineCallbacks
    def scroll_text(self, disp, text):
        if self._is_scrolling:
            return
        self._is_scrolling = True
        s = text + "    "
        for i in range(len(s)):
            disp.setMessage(s[i:i + 4])
            yield sleep(.2)
        self._is_scrolling = False

    @inlineCallbacks
    def onJoin(self, details):

        self._tick_sent = {}
        self._is_scrolling = False

        extra = self.config.extra

        self._serial = get_serial()
        self._my_ip = get_ip_address()
        self._joined_at = time.strftime("%H:%M")

        self._app_prefix = u'io.crossbar.demo.wpad'
        self._prefix = u'{}.wpad.{}'.format(self._app_prefix, self._serial)

        self.log.info("Crossbar.io IoT Starterkit Serial No.: {serial}",
                      serial=self._serial)
        self.log.info("WPad connected: {details}", details=details)

        # setup Neopixel LED strip
        self._ledstrip = Adafruit_NeoPixel(
            extra['led_count'], extra['led_pin'], extra['led_freq_hz'],
            extra['led_dma'], extra['led_invert'], extra['led_brightness'])

        self._ledstrip.begin()

        # setup GPIO
        GPIO.setwarnings(False)
        pinmode = extra.get("pin_mode", "bcm")
        if pinmode in WPad.PINMODES:
            GPIO.setmode(WPad.PINMODES[pinmode])
        else:
            GPIO.setmode(GPIO.BCM)
        GPIO.cleanup()

        self._row_pins = extra.get("row_pins", [])
        for pin in self._row_pins:
            GPIO.setup(pin, GPIO.OUT)
        self._select_row(0)

        # setup ADC
        self._adc = Adafruit_ADS1x15.ADS1015()

        def log_adc():
            # read values from ADC
            values = []
            for i in range(4):
                values.append(self._adc.read_adc(i, gain=8))

            # normalize values
            nvalues = [
                round(100. * ((2048. - float(x)) / 2048.), 3) for x in values
            ]
            nvalues = [nvalues[2], nvalues[3], nvalues[1], nvalues[0]]

            # illuminate neopixel strip
            for i in range(4):
                col = int(round(255. * float(nvalues[i]) / 100.))
                self._ledstrip.setPixelColorRGB(i * 2, col, col, col)
                self._ledstrip.setPixelColorRGB(i * 2 + 1, col, col, col)
            self._ledstrip.show()

            # publish WAMP event
            self.publish(u'{}.on_wpad'.format(self._prefix), nvalues)

        scan_rate = float(extra.get(u'scan_rate', 50))
        self.log.info('Scanning sensors with {} Hz ..'.format(scan_rate))
        LoopingCall(log_adc).start(1. / scan_rate)

        self._cpu_load = deque()
        for i in range(self._ledstrip.numPixels()):
            self._cpu_load.append(0)

        # our quad, alphanumeric display: https://www.adafruit.com/products/2157
        self._disp = QuadAlphanum(extra[u'i2c_address'])
        self._disp.clear()
        self._disp.setBrightness(int(round(extra[u'brightness'] * 15)))

        @inlineCallbacks
        def displayNotice():
            yield self.scroll_text(
                self._disp, "IP {} ({})    ".format(self._my_ip,
                                                    self._joined_at).upper())

        # every couple of secs, display a notice
        LoopingCall(displayNotice).start(53)

        def on_tick(tick_no):
            if tick_no in self._tick_sent:
                rtt = 1000. * (time.time() - self._tick_sent[tick_no])
                del self._tick_sent[tick_no]
            else:
                rtt = None
            self.log.info('TICK received [tick {}, rtt {}]'.format(
                tick_no, rtt))
            self.flash(r=0, g=255, b=0, repeat=1)

        yield self.subscribe(on_tick, u'{}.on_alive'.format(self._prefix))

        self._tick_no = 0
        self._tick_loop = LoopingCall(self._tick)
        self._tick_loop.start(7)

        LoopingCall(self.show_load).start(1)

        # signal we are done with initializing our component
        self.publish(u'{}.on_ready'.format(self._prefix))
        self.log.info("WPad ready.")

        self.flash()

    def onLeave(self, details):
        self.log.info("Session closed: {details}", details=details)
        self.disconnect()

    def onDisconnect(self):
        self.log.info("Connection closed")
        try:
            reactor.stop()
        except ReactorNotRunning:
            pass
Beispiel #35
0
class Display(object):
    """
    Args:
        gpio_pin (int): which GPIO pin the data should be sent on.
                        Note: this is not the physical pin number
                        nor the WiringPi number.

    Keyword Args:
        led_frequency (int): the frequency of the LED strand (hertz)
        dma (int): the DMA channel to use for generating the signal. DO NOT
                   use 5 on the Pi 3 as this has been known to corrupt files.
        initial_brightness (int): the initial brightness setting of the LEDs.
                                  should be a value between 0 and 255.
        invert (bool): Set to ``True`` to invert the signal (when using NPN
                       transistor level shift)
        channel (int): set to ``1`` for GPIOs 13, 19, 41, 45, or 53
    """
    def __init__(self,
                 rows,
                 cols,
                 gpio_pin,
                 led_frequency=800000,
                 dma=10,
                 initial_brightness=255,
                 invert=False,
                 channel=0):
        self.initial_brightness = initial_brightness
        self.pixels = self.setup(rows, cols)

        pixel_count = len(self.pixels)
        self.count = pixel_count
        self.num_rows = rows
        self.num_cols = cols

        for pixel in self.pixels:
            pixel.brightness = initial_brightness

        self.strand = None
        self.setup_strand(gpio_pin, pixel_count, led_frequency, dma,
                          initial_brightness, invert, channel)

    def setup(self, rows, cols):
        raise NotImplementedError()

    def setup_strand(self, gpio_pin, pixel_count, led_frequency, dma,
                     initial_brightness, invert, channel):
        from neopixel import Adafruit_NeoPixel
        self.strand = Adafruit_NeoPixel(pixel_count, gpio_pin, led_frequency,
                                        dma, invert, initial_brightness,
                                        channel)
        self.strand.begin()

    def fill(self, red, green, blue, brightness=255):
        for pixel in self.pixels:
            pixel.red = red
            pixel.green = green
            pixel.blue = blue
            pixel.brightness = brightness

    def pixel_at(self, row, column):
        return self.pixels[row * self.num_rows + column]

    def show(self):
        for pixel in self.pixels:
            self.strand._led_data[pixel.id] = pixel.render()
        self.strand.show()

    def clear(self):
        for pixel in self.pixels:
            pixel.clear()

        self.show()

    def itergrid(self):
        for row in range(self.num_rows):
            for col in range(self.num_cols):
                yield row, col, self.pixel_at(row, col)