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 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)
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_
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)
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 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))
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()
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 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()
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
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()
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
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 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 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 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()
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()
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()
# divides evenly into the number of pixels, or vice versa, # the lights won't advance and that's boring to watch. # In that case, add a black pixel. tot_hits = sum(keywords_found[i] for i in keywords_found) if 'flash' in keywords_found: tot_hits -= keywords_found['flash'] if num_pixels % tot_hits == 0 or tot_hits % num_pixels == 0: keywords_found['blank'] = 1 # Loop over the topics: for topic in keywords_found: if topic == 'flash': totdiv = int(tot_time) / FLASHFRAC if totdiv > lastflash: lastflash = totdiv for i in range(keywords_found[topic]): flash(strip, flashcolor) # XXX Add the time we flashed to tot_time continue # For this topic, keywords_found[topic] is the number of keywords # we matched on Twitter. Show that number of pixels. # The color for this topic is topiccolors[topic]. for i in range(keywords_found[topic]): strip.setPixelColor(led_number, topiccolors[topic]) strip.show() led_number = (led_number + 1) % num_pixels time.sleep(TIME_BETWEEN_PIXELS) tot_time += TIME_BETWEEN_PIXELS
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()
from neopixel import ws, Adafruit_NeoPixel, Color import config strip = Adafruit_NeoPixel( config.N_PIXELS, config.LED_PIN, config.LED_FREQ_HZ, config.LED_DMA, config.LED_INVERT, config.BRIGHTNESS, config.LED_CHANNEL, ws.WS2811_STRIP_GRB ) strip.begin() strip.setPixelColor(30, Color(255, 0, 0)) strip.show()
arg1 = [i for i in range(0, 255, 4)] arg2 = [i for i in range(0, 255, 4)] arg3 = [i for i in range(0, 255, 4)] lst = [1, 2, 3, 4, 5] lights = [l for i in range(int(round(len(arg1) / len(lst)))) for l in lst] del lights[-1] count = 0 while (count < 60): for i, li, ar1, ar2, ar3, in zip(range(strip.numPixels()), lights, arg1, arg2, arg3): print(i, li, 'on') strip.setPixelColor(li, Color(ar1, ar2, ar3)) strip.show() time.sleep(1) strip.setPixelColor(li, Color(ar1, ar2, ar3)) strip.show() time.sleep(1) strip.setPixelColor(li, Color(ar1, ar2, ar3)) strip.show() time.sleep(1) strip.setPixelColor(li, Color(ar1, ar2, ar3)) strip.show() time.sleep(1) strip.setPixelColor(li, Color(ar1, ar2, ar3)) strip.show() time.sleep(1) count += 1