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()
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()
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))
def _get_strip(): strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS) strip.begin() for i in range(0, strip.numPixels(), 1): strip.setPixelColor(i, Color(0, 0, 0)) strip.setBrightness(100) return strip
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()
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()
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 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
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') 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 = '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, 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' ) 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 == '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 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()
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 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()