示例#1
0
class NeoPixels(object):
    LED_COUNT = 256  # Number of LED pixels.
    LED_PIN = 21  # GPIO pin connected to the pixels (must support PWM!). 18=PWM, 21=PCM, 10=SPI-MOSI
    LED_FREQ_HZ = 800000  # LED signal frequency in hertz (usually 800khz)
    LED_DMA = 5  # DMA channel to use for generating signal (try 5)
    LED_BRIGHTNESS = 255  # Set to 0 for darkest and 255 for brightest
    LED_INVERT = False  # True to invert the signal (when using NPN transistor level shift)

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

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

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

    def write_pixels(self, data):
        for y, row in enumerate((data * 255).astype(np.uint8)):
            for x, color in enumerate(row):
                self._pixels.setPixelColorRGB(y * 16 + x, *color)
        self._pixels.show()
示例#2
0
class NeoPixelRenderer(Renderer):
    def __init__(self, led_dma=10, led_strip=ws.WS2811_STRIP_GRB):
        super(NeoPixelRenderer, self).__init__()

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

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

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

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

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

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

            self.strip.show()
示例#3
0
def exc():
    import os
    import json
    import math
    import time
    from copy import deepcopy
    from neopixel import Adafruit_NeoPixel
    basedir = os.path.dirname(os.path.realpath(__file__))

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

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

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

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

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

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

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

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

    with open(basedir + '/ledstate.json', 'w') as out:
        out.write(json.dumps(old))
示例#4
0
文件: general.py 项目: indietyp/IoP
  def run(steps=120):
    result = VariousTools.offline_check('generalleds', hardware=False)
    changelog = [0, 0, 0]
    if result:
      setting = {'threat': 0, 'cautioning': 0, 'optimum': 0}
      plant = Plant.get(localhost=True)

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

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

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

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

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

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

      current = current[::-1]

    if changelog == current:
      return True

    bcurrent = []
    bchange = []

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

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

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

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

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

    return True
class LedController:

    global debug

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

        self.current_beat_index = 0

        self.note_led_rows = []

        self.number_of_led_strips = number_of_led_strips
        self.number_of_leds_per_strip = number_of_leds_per_strip

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

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

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

        self.led_strip = None

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

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

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

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

    def remove_strip_obj(self):
        self.led_strip = None

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

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

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

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

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

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

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

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

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

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

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

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

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

        self.set_led_colors()
        self.update_led_strip_colors()

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

        self.display_updated_leds()
示例#6
0
class WPad(ApplicationSession):
    """
    Connects the Pi's GPIOs to WAMP.
    """
    PINMODES = {'bcm': GPIO.BCM, 'board': GPIO.BOARD}

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

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

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

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

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

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

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

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

    @inlineCallbacks
    def onJoin(self, details):

        self._tick_sent = {}
        self._is_scrolling = False

        extra = self.config.extra

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

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

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

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

        self._ledstrip.begin()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        LoopingCall(self.show_load).start(1)

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

        self.flash()

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

    def onDisconnect(self):
        self.log.info("Connection closed")
        try:
            reactor.stop()
        except ReactorNotRunning:
            pass
示例#7
0
class ColoramaDisplay(ApplicationSession):
    @inlineCallbacks
    def onJoin(self, details):

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

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

        # get custom configuration
        cfg = self.config.extra

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

        self._leds.begin()

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

        self.flash()

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

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

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

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

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

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

    @inlineCallbacks
    def rainbow(self, wait_ms=20, iterations=1):
        """Draw rainbow that fades across all pixels at once."""
        for j in range(256 * iterations):
            for i in range(self._leds.numPixels()):
                r, g, b = self.wheel((i + j) & 255)
                self.set_color(r, g, b, i)
            yield sleep(wait_ms / 1000.0)

    @inlineCallbacks
    def rainbow_cycle(self, wait_ms=20, iterations=5):
        """Draw rainbow that uniformly distributes itself across all pixels."""
        for j in range(256 * iterations):
            for i in range(self._leds.numPixels()):
                r, g, b = self.wheel(((i * 256 / self._leds.numPixels()) + j)
                                     & 255)
                self.set_color(r, g, b, i)
            yield sleep(wait_ms / 1000.0)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def draw_maze(self, *args, **kwargs):
        super().draw_maze(*args, **kwargs)
        self.draw_maze_leds()
        return True
示例#9
0
class ColoramaDisplay(ApplicationSession):

    @inlineCallbacks
    def onJoin(self, details):

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

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

        # get custom configuration
        cfg = self.config.extra

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

        self._leds.begin()

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

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

        self.flash()

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

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

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

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

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

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

    @inlineCallbacks
    def rainbow(self, wait_ms=20, iterations=1):
        """Draw rainbow that fades across all pixels at once."""
        for j in range(256 * iterations):
            for i in range(self._leds.numPixels()):
                r, g, b = self.wheel((i + j) & 255)
                self.set_color(r, g, b, i)
            yield sleep(wait_ms / 1000.0)

    @inlineCallbacks
    def rainbow_cycle(self, wait_ms=20, iterations=5):
        """Draw rainbow that uniformly distributes itself across all pixels."""
        for j in range(256 * iterations):
            for i in range(self._leds.numPixels()):
                r, g, b = self.wheel(((i * 256 / self._leds.numPixels()) + j) & 255)
                self.set_color(r, g, b, i)
            yield sleep(wait_ms / 1000.0)

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

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

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

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

    def onDisconnect(self):
        self.log.info("Connection closed")
        for i in range(self._leds.numPixels()):
            self._leds.setPixelColorRGB(i, 0, 0, 0)
        self._leds.show()
        try:
            reactor.stop()
        except ReactorNotRunning:
            pass
示例#10
0
from gpiozero import MCP3008
from time import sleep
from neopixel import Adafruit_NeoPixel

r = MCP3008(channel=0)
g = MCP3008(channel=1)
b = MCP3008(channel=2)
LEDS = 12
PIN = 18

strip = Adafruit_NeoPixel(LEDS, PIN)
strip.begin()

while True:
    red = round(r.value * 255)
    green = round(g.value * 255)
    blue = round(b.value * 255)
    print(red, green, blue)
    for i in range(LEDS):
        strip.setPixelColorRGB(i, red, green, blue)
        strip.show()
    sleep(0.1)