Exemple #1
0
    def start(self):
        """This method does the actual work."""
        try:
            strip = apa102.APA102(num_led=self.num_led,
                                  global_brightness=self.global_brightness,
                                  mosi=self.MOSI,
                                  sclk=self.SCLK,
                                  order=self.order)  # Initialize the strip

            self.init(strip, self.num_led)  # Call the subclasses init method
            strip.show()
            current_cycle = 0
            continue_loop = 1
            while modes[mode_number] == "theater_chase":
                for current_step in range(self.num_steps_per_cycle):
                    continue_loop = self.update(strip, self.num_led,
                                                self.num_steps_per_cycle,
                                                current_step, current_cycle)
                    if modes[mode_number] == "theater_chase":
                        strip.show()  # repaint if required
                    else:
                        break
                    time.sleep(self.pause_value)  # Pause until the next step
        except KeyboardInterrupt:
            print('Interupted...')
            self.cleanup(strip)
Exemple #2
0
    def __init__(self,
                 pin_fancontrol=18,
                 pin_button=17,
                 button_poll_delay=0.05,
                 disable_button=False,
                 disable_led=False):
        """FAN Shim.

        :param pin_fancontrol: BCM pin for fan on/off
        :param pin_button: BCM pin for button

        """
        self._pin_fancontrol = pin_fancontrol
        self._pin_button = pin_button
        self._poll_delay = button_poll_delay
        self._button_press_handler = None
        self._button_release_handler = None
        self._button_hold_handler = None
        self._button_hold_time = 2.0
        self._t_poll = None

        self._disable_button = disable_button
        self._disable_led = disable_led

        GPIO.setwarnings(False)
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(self._pin_fancontrol, GPIO.OUT)

        if not self._disable_button:
            GPIO.setup(self._pin_button, GPIO.IN, pull_up_down=GPIO.PUD_UP)

        if not self._disable_led:
            self._led = apa102.APA102(1, 15, 14, None, brightness=0.05)

        atexit.register(self._cleanup)
Exemple #3
0
 def __init__(self, dueros):
     self.namespace = "ai.dueros.device_interface.thirdparty.speaker.led"
     self.dueros = dueros
     self.power = LED(5)
     self.power.on()
     self.dev = apa102.APA102(num_led=self.PIXELS_N)
     self.dev.clear_strip()
Exemple #4
0
    def start(self):
        try:
            strip = apa102.APA102(numLEDs=self.numLEDs,
                                  globalBrightness=self.globalBrightness,
                                  order=self.order)  # Initialize the strip
            strip.clearStrip()
            self.init(strip, self.numLEDs)  # Call the subclasses init method
            strip.show()
            currentCycle = 0
            while True:  # Loop forever (no 'for' here due to the possibility of infinite loops)
                for currentStep in range(self.numStepsPerCycle):
                    needRepaint = self.update(
                        strip, self.numLEDs, self.numStepsPerCycle,
                        currentStep,
                        currentCycle)  # Call the subclasses update method
                    if (needRepaint): strip.show()  # Display, only if required
                    time.sleep(self.pauseValue)  # Pause until the next step
                currentCycle += 1
                if (self.numCycles != -1):
                    if (currentCycle >= self.numCycles): break
            # Finished, cleanup everything
            self.cleanup(strip)

        except KeyboardInterrupt:  # Ctrl-C can halt the light program
            print('Interrupted...')
            self.cleanup(strip)
Exemple #5
0
def process_json(message):
    strip = apa102.APA102(machine.Pin(APA102_PIN_CI),
                          machine.Pin(APA102_PIN_DI),
                          APA102_PIXELS)
    parsed = ujson.loads(message)
    
    if 'r' not in parsed:
        parsed['r'] = DEFAULT_REPEAT
    if 's' not in parsed:
        parsed['s'] = DEFAULT_SLEEP
    
    for _ in range(parsed['r']):
        for frame in parsed['f']:
            if isinstance(frame, int):
                for _ in range(frame):
                    time.sleep(parsed['s'])
            else:
                strip.fill([0, 0, 0, 0])
                i = 0
                for pixel in frame:
                    if isinstance(pixel, int):
                        # repeat pixel mode
                        last_pixel = strip[i - 1] if i >= 1 else (0, 0, 0, 0)
                        for _ in range(pixel):
                            strip[i] = last_pixel
                            i += 1
                    else:
                        strip[i] = pixel
                        i += 1
                strip.write()
                time.sleep(parsed['s'])
    strip.fill([0, 0, 0, 0])
    strip.write()
    def __init__(self, num_pixels, num_rows=1, brightness=31):
        super().__init__(num_pixels, num_rows)
        """Creates an APA102-based output device

        Parameters
        ----------
        pixels: int
            Number of LED strip pixels
        brightness: int, optional
            Global brightness
        """
        try:
            import apa102
        except ImportError as e:
            url = 'https://github.com/tinue/APA102_Pi'
            logger.error('Could not import the apa102 library')
            logger.error('For installation instructions, see {}'.format(url))
            raise e
        self._strip = apa102.APA102(
            numLEDs=num_pixels,
            globalBrightness=brightness)  # Initialize the strip
        led_data = np.array(self._strip.leds, dtype=np.uint8)
        # memoryview preserving the first 8 bits of LED frames (w/ global brightness)
        self._strip.leds = led_data.data
        # 2D view of led_data
        self.led_data = led_data.reshape((num_pixels, 4))  # or (-1, 4)
Exemple #7
0
    def start(self):
        """This method does the actual work."""
        try:
            strip = apa102.APA102(num_led=self.num_led,
                                  global_brightness=self.global_brightness,
                                  mosi=self.mosi,
                                  sclk=self.sclk,
                                  order=self.order)  # Initialize the strip
            strip.clear_strip()
            self.init(strip, self.num_led)  # Call the subclasses init method
            strip.show()
            current_cycle = 0
            while True:  # Loop forever
                for current_step in range(self.num_steps_per_cycle):
                    need_repaint = self.update(strip, self.num_led,
                                               self.num_steps_per_cycle,
                                               current_step, current_cycle)
                    if need_repaint:
                        strip.show()  # repaint if required
                    time.sleep(self.pause_value)  # Pause until the next step
                current_cycle += 1
                if self.num_cycles != -1:
                    if current_cycle >= self.num_cycles:
                        break
            # Finished, cleanup everything
            self.cleanup(strip)

        except KeyboardInterrupt:  # Ctrl-C can halt the light program
            print('Interrupted...')
            self.cleanup(strip)
Exemple #8
0
 def startLoop(self):
     self.strip = apa102.APA102(numLEDs=self.numLEDs,
                                globalBrightness=self.globalBrightness,
                                order=self.order)  # Initialize the strip
     self.strip.clearStrip()
     self.init(self.strip, self.numLEDs)  # Call the subclasses init method
     self.strip.show()
     self.currentCycle = 0
 def __init__(self, width=8, height=1, cascaded=1):
     self.strip = apa102.APA102(machine.Pin(5), machine.Pin(4),
                                width * height * cascaded)
     self.width = width
     self.height = height
     self.cascaded = cascaded
     self.intesity = 1
     self.backcolor = (0, 0, 0)
Exemple #10
0
def test_setup_spi(GPIO, spidev):
    import apa102

    lights = apa102.APA102(3, 10, 11, 8)

    spidev.SpiDev.assert_has_calls((mock.call(0, 0), ))

    del lights
Exemple #11
0
    def __init__(self):
        self.dev = apa102.APA102(num_led=self.PIXELS_N)

        self.power = LED(5)
        self.power.on()

        self.thread = threading.Thread(target=self._run)
        self.thread.daemon = True
        self.thread.start()
Exemple #12
0
    def __init__(self):
        self.power = LED(5)
        self.power.on()

        # Initialize the library and the strip
        self.strip = apa102.APA102(num_led=12, global_brightness=31)

        # Turn off all pixels (sometimes a few light up when the strip gets power)
        self.strip.clear_strip()
Exemple #13
0
 def __init__(self, pattern=GoogleHomeLedPattern):
     self.pattern = pattern(show=self.show)
     self.dev = apa102.APA102(num_led=self.PIXELS_N)
     self.power = LED(5)
     self.power.on()
     self.queue = Queue.Queue()
     self.t4 = threading.Thread(target=self._run)
     self.t4.daemon = True
     self.t4.start()
     self.last_direction = None
Exemple #14
0
    def __init__(self):
        self.basis = [0] * 3 * self.PIXELS_N
        self.basis[3], self.basis[4] = 2, 2
        self.colors = [0] * 3 * self.PIXELS_N
        self.dev = apa102.APA102(num_led=self.PIXELS_N)

        self.next = threading.Event()
        self.queue = Queue.Queue()
        self.thread = threading.Thread(target=self._run)
        self.thread.daemon = True
        self.thread.start()
Exemple #15
0
    def __init__(self, pattern=AlexaLedPattern):
        self.pattern = pattern(show=self.show)

        self.dev = apa102.APA102(num_led=self.PIXELS_N)

        self.queue = Queue.Queue()
        self.thread = threading.Thread(target=self._run)
        self.thread.daemon = True
        self.thread.start()

        self.last_direction = None
Exemple #16
0
    def _configure(self):
        """
        Configure module
        """
        #configure button
        if self._get_config_field(u'button_gpio_uuid') is None:
            self.__configure_button()

        #play blink green at startup
        if self.seeed2mic_driver.is_installed():
            self.leds_driver = apa102.APA102(num_led=3)
            self.play_leds_profile(self.LEDS_PROFILE_BLINK_GREEN)
Exemple #17
0
def test_setup_gpio_inverted(GPIO, spidev):
    import apa102

    lights = apa102.APA102(3, 2, 3, 4, invert=True)

    GPIO.setmode.assert_has_calls((mock.call(GPIO.BCM), ))

    GPIO.setup.assert_has_calls(
        (mock.call(2, GPIO.OUT,
                   initial=1), mock.call(3, GPIO.OUT,
                                         initial=1), mock.call(4, GPIO.OUT)))

    del lights
Exemple #18
0
def test_setup_force_gpio(GPIO, spidev):
    import apa102

    lights = apa102.APA102(3, 10, 11, 8, force_gpio=True)

    GPIO.setmode.assert_has_calls((mock.call(GPIO.BCM), ))

    GPIO.setup.assert_has_calls(
        (mock.call(10, GPIO.OUT,
                   initial=0), mock.call(11, GPIO.OUT,
                                         initial=0), mock.call(8, GPIO.OUT)))

    del lights
Exemple #19
0
def start_server():
    global LED_colourBuffer, led
    try:
        led = apa102.APA102(1, 15, 14, None, brightness=0.05)
    except:
        pass
    while True:
        try:
            colour = LED_colourBuffer.get()
            setLedColour(colour)
        except KeyboardInterrupt:
            break
        except:
            pass
def test_show_gpio(GPIO, spidev):
    import apa102

    lights = apa102.APA102(3, 10, 11, 8, force_gpio=True)

    lights.set_pixel(0, 255, 0, 0)
    lights.set_pixel(1, 0, 255, 0)
    lights.set_pixel(2, 0, 0, 255)

    lights.show()

    assert GPIO.output.call_count == 4898  # Count of pin transitions

    del lights
Exemple #21
0
    def __init__(self, pattern=MagicEcoLedPattern):
        self.pattern = pattern(show=self.show, show_odd_pixel=self.show_odd_pixel)

        self.dev = apa102.APA102(num_led=self.PIXELS_N)
        
        self.power = LED(5)
        self.power.on()

        self.queue = Queue.Queue()
        self.thread = threading.Thread(target=self._run)
        self.thread.daemon = True
        self.thread.start()

        self.last_direction = None
Exemple #22
0
def test_setup_gpio(GPIO, spidev):
    import apa102

    lights = apa102.APA102(3, 2, 3, 4)

    GPIO.setmode.assert_has_calls((
        mock.call(GPIO.BCM),
    ))

    GPIO.setup.assert_has_calls((
        mock.call([2, 3], GPIO.OUT),
        mock.call(4, GPIO.OUT)
    ))

    del lights
Exemple #23
0
def test_show_spi(GPIO, spidev):
    import apa102

    lights = apa102.APA102(3, 10, 11, 8)

    spidev.SpiDev.assert_has_calls((mock.call(0, 0), ))

    lights.set_pixel(0, 255, 0, 0)
    lights.set_pixel(1, 0, 255, 0)
    lights.set_pixel(2, 0, 0, 255)

    lights.show()

    spidev.SpiDev(0, 0).xfer3.assert_has_calls((mock.call(lights._buf), ))

    del lights
    def start(self):
        """This method does the actual work."""

        # If there are no updaters, then revert to the old inheritence-based behavior.
        if len(self.updaters) == 0:
            self.updaters.append(self.update)

        try:
            strip = apa102.APA102(num_led=self.num_led,
                                  global_brightness=self.global_brightness,
                                  mosi=self.mosi,
                                  sclk=self.sclk,
                                  order=self.order)  # Initialize the strip
            strip.clear_strip()
            self.init(strip, self.num_led)  # Call the subclasses init method
            strip.show()
            current_cycle = 0
            next_time = time.time()
            end_time = next_time + self.duration_s if self.duration_s > 0 else None
            while True:  # Loop forever
                for current_step in range(self.num_steps_per_cycle):
                    need_repaint = sum(
                        (update(strip, self.num_led, self.num_steps_per_cycle,
                                current_step, current_cycle)
                         for update in self.updaters))
                    time.sleep(max(0, next_time - time.time()))
                    next_time += self.pause_value
                    if need_repaint:
                        strip.show()  # repaint if required
                    if end_time and time.time() > end_time:
                        break
                if end_time and time.time() > end_time:
                    break
                time.sleep(max(0, next_time - time.time()))  # Final hold
                current_cycle += 1
                if self.num_cycles != -1 and current_cycle >= self.num_cycles:
                    break
            # Finished, cleanup everything
            self.cleanup(strip)

        except KeyboardInterrupt:  # Ctrl-C can halt the light program
            print('Interrupted...')
            self.cleanup(strip)
            raise
Exemple #25
0
 def __init__(self, pattern=GoogleHomeLedPattern):
     self.pattern = pattern(show=self.show)
     #这个是驱动程序,apa102为led的驱动程序
     self.dev = apa102.APA102(num_led=self.PIXELS_N)
     #配置led灯的引脚号,这里是5,不可改变
     self.power = LED(5)
     self.power.on()
     self.queue = Queue.Queue()
     #创建一个线程
     #target为需要线程去执行的方法名
     #args参数为线程执行方法接收的参数,该属性是一个元组,如果只有一个参数也需要在末尾加
     #逗号
     self.thread = threading.Thread(target=self._run)
     #开启线程的守护进程,设置为True
     self.thread.daemon = True
     #启动这个线程
     self.thread.start()
     #这里记录最后一次的方位,这个4mic通过这个参数定位声音来源的方位
     self.last_direction = None
Exemple #26
0
def background(arg):
  global running, lights, new_data, numLEDs
  strip = apa102.APA102(numLEDs=numLEDs, globalBrightness=15, order="rgb") # Initialize the strip
  strip.clearStrip()
  strip.show()
  while running:
    if(new_data):
      try:
        for i in range(0, numLEDs):
          strip.setPixelRGB(i,lights[i])
        new_data = False
        strip.show()
      except:
        import traceback
        print(traceback.format_exc())
        print("Failed to run")
    else:
      sleep(0.03)
  strip.cleanup()
 def __init__(self, num_pixels, visualize_only=False, visualizer_obj=None):
     self.buffer_lock = threading.Lock()
     self.data_segments = []
     self.end_colors = {
         0: (0xFF, 0xFF, 0xFF),
         1: (0xF5, 0xE7, 0xE7),
         2: (0xEC, 0xD0, 0xD0),
         3: (0xE3, 0xB9, 0xB9),
         4: (0xD9, 0xA2, 0xA2),
         5: (0xD0, 0x8B, 0x8B),
         6: (0xC7, 0x73, 0x73),
         7: (0xBE, 0x5C, 0x5C),
         8: (0xB4, 0x45, 0x45),
         9: (0xAB, 0x2E, 0x2E),
         10: (0xA2, 0x17, 0x17),
         11: (0x99, 0, 0)
     }
     self.interpolated_loudness_buffer = []
     self.interpolated_pitch_buffer = []
     self.num_pixels = num_pixels
     self.permission_scopes = "user-modify-playback-state user-read-currently-playing user-read-playback-state"
     self.playback_pos = 0
     self.pos_lock = threading.Lock()
     self.should_terminate = False
     self.sp_gen = self.sp_load = self.sp_skip = self.sp_sync = self.sp_vis = None
     self.start_color = (0, 0, 255)
     if not visualize_only:
         self.strip = apa102.APA102(num_led=num_pixels,
                                    global_brightness=23,
                                    mosi=10,
                                    sclk=11,
                                    order='rgb')
     else:
         self.strip = visualizer_obj
     self.track = None
     self.track_duration = None
Exemple #28
0
import apa102
import time

pixels = apa102.APA102(num_led=3)
pixels.set_pixel(0, 255, 0, 0)
pixels.set_pixel(1, 0, 255, 0)
pixels.set_pixel(2, 0, 0, 255)
pixels.show()

time.sleep(1)

pixels.set_pixel(0, 0, 0, 0)
pixels.set_pixel(1, 0, 0, 0)
pixels.set_pixel(2, 0, 0, 0)
pixels.show()
Exemple #29
0
#!/usr/bin/env python3
import apa102
import time
import paho.mqtt.client as mqtt
import RPi.GPIO as GPIO
import json
from threading import Thread

#########################################################################
# Dieses Skript hoert auf MQTT Nachrichten, die von Snips gesendet werden,
# und steuert damit die LEDs des Sprachassistenten
# Es soll automatisch beim Boot ausgefuehrt werden
#########################################################################

led = apa102.APA102(num_led=3)
hotword_active = True
stop_thread = False
thread_running = False

GPIO.setmode(GPIO.BCM)
GPIO.setup(12, GPIO.OUT)
GPIO.setup(13, GPIO.OUT)

gpio_blue = GPIO.PWM(12, 120)
gpio_red = GPIO.PWM(13, 120)
gpio_blue.start(0)
gpio_red.start(0)


# mit dieser methode werden die LEDs auf dem ReSpeaker gesteuert
# color erwartet eine farbe in form einer liste
Exemple #30
0
                        strip[i] = pixel
                        i += 1
                strip.write()
                time.sleep(parsed['s'])
    strip.fill([0, 0, 0, 0])
    strip.write()


def handle_mqtt_message(topic, message):
    if topic == MQTT_PREFIX + b'json':
        process_json(message)


if __name__ == '__main__':
    strip = apa102.APA102(machine.Pin(APA102_PIN_CI),
                              machine.Pin(APA102_PIN_DI),
                              APA102_PIXELS)
    strip.fill([0, 0, 0, 0])
    strip.write()
    del strip
    wlan = network.WLAN(network.STA_IF)
    while not wlan.isconnected():
        pass  # Wait until connected to wifi
    mqtt = MQTTClient("gyro", MQTT_BROKER)
    mqtt.set_callback(handle_mqtt_message)
    mqtt.connect()
    mqtt.subscribe(MQTT_PREFIX + b'json')
    while True:
        try:
            mqtt.wait_msg()
        except: