Example #1
0
class Strip:
    def __init__(self):
        self.strip = Adafruit_NeoPixel(
            LED_COUNT,
            LED_PIN,
            LED_FREQ_HZ,
            LED_DMA,
            LED_INVERT,
            LED_BRIGHTNESS,
            LED_CHANNEL,
        )
        self.strip.begin()

    def clear(self):
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(i, Color.rgb(0, 0, 0).toLED())
        self.show()

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

    def set_color(self, obj):
        if type(obj) == Key:
            self.strip.setPixelColor(obj.led_index, obj.led.color.toLED())
        elif type(obj) == Keyboard:
            for key in obj.keys:
                if key.led.color:
                    self.strip.setPixelColor(key.led_index,
                                             key.led.color.toLED())
Example #2
0
class LedsNeoPixel(LedsSoft):  # pragma: no cover
    LED_PIN = 13  # GPIO pin connected to the pixels (18 uses PWM!).
    LED_FREQ_HZ = 800000  # LED signal frequency in hertz (usually 800khz)
    LED_DMA = 12  # DMA channel to use for generating signal (try 10)
    LED_BRIGHTNESS = 200  # Set to 0 for darkest and 255 for brightest
    # True to invert the signal (when using NPN transistor level shift)
    LED_INVERT = False
    LED_CHANNEL = 1  # set to '1' for GPIOs 13, 19, 41, 45 or 53
    LED_COUNT = 5

    PULSING_RATE = 0.100  # every 100ms

    def __init__(self):
        super().__init__()
        self.strip = Adafruit_NeoPixel(
            LedsNeoPixel.LED_COUNT,
            LedsNeoPixel.LED_PIN,
            LedsNeoPixel.LED_FREQ_HZ,
            LedsNeoPixel.LED_DMA,
            LedsNeoPixel.LED_INVERT,
            LedsNeoPixel.LED_BRIGHTNESS,
            LedsNeoPixel.LED_CHANNEL,
        )
        # Intialize the library (must be called once before other functions).
        self.strip.begin()

    def do_set(self, led, red, green, blue):
        # NeoPixel indexes on the strip do match the (original) values
        led_ix = led.value
        self.strip.setPixelColor(led_ix, Color(red, green, blue))

    def do_show(self):
        self.strip.show()
Example #3
0
def main(agent_id):
    # 根据agent_id点亮不同位置的灯区分树莓派 1 2 3
    print('suceess0:the number of this pi is %d:', agent_id)
    strip = Adafruit_NeoPixel(32, 18, 800000, 10, False, 10)
    strip.begin()
    strip.setPixelColor(agent_id, Color(255, 0, 0))
    strip.show()

    context = zmq.Context()
    publisher = context.socket(zmq.PUB)
    publisher.connect("tcp://%s:5556" % broker_ip)
    print("success1: begin zmq")
    subscriber = context.socket(zmq.SUB)
    subscriber.connect("tcp://%s:5555" % broker_ip)
    # subscriber.setsockopt_string(zmq.SUBSCRIBE, str(agent_id))
    while True:
        flag = 0
        #message = subscriber.recv()
        r = scan_wifi()
        print("success2:scan_wifi")
        info = r.readlines()
        print("success3:read lines")
        for line in info:
            line = line.strip('\r\n')
            # print(line)
            mac = line[0:17]
            # 移动终端的mac地址
            if (mac == '54:25:ea:4c:22:c0') | (mac == '74:60:fa:81:a8:d8'):
                print('%d: %s' % (agent_id, line))
                publisher.send_string('%d: %s' % (13, line))
                flag = 1
        if flag == 0:
            print('haha')
            time.sleep(0.2)
Example #4
0
def set_leds(shutdown):
    LED_COUNT = 5
    LED_PIN = 13  # GPIO pin connected to the pixels (18 uses PWM!).
    LED_FREQ_HZ = 800000  # LED signal frequency in hertz (usually 800khz)
    LED_DMA = 12  # DMA channel to use for generating signal (try 10)
    LED_BRIGHTNESS = 200  # 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 = 1  # set to '1' for GPIOs 13, 19, 41, 45 or 53

    strip = Adafruit_NeoPixel(
        LED_COUNT,
        LED_PIN,
        LED_FREQ_HZ,
        LED_DMA,
        LED_INVERT,
        LED_BRIGHTNESS,
        LED_CHANNEL,
    )
    # Intialize the library (must be called once before other functions).
    strip.begin()

    if shutdown:
        color = Color(0, 0, 0)
    else:
        color = Color(255, 0, 255)

    for led in range(6):
        strip.setPixelColor(led, color)

    strip.show()
class LedsModule(BaseModule):
    def __init__(self, config_file, secure_file):
        BaseModule.__init__(self, config_file, secure_file)

        try:
            self.neopixel_pin = self.config['neopixel_pin']
        except KeyError as e:
            logger = logging.getLogger(__name__)
            err = "Key error in LEDS Init: {}".format(e)
            logger.error(err)
            self.mqtt_client.publish('gserv/error', err)
            sys.exit(2)

        self.pattern_classes = {
            "BLANK": SolidPattern,
            "GREEN_CLOCKWISE": SpinPattern,
            "GREEN_COUNTERCLOCKWISE": SpinPattern,
            "RED_CLOCKWISE": SpinPattern,
            "RED_COUNTERCLOCKWISE": SpinPattern,
            "BLUE_CLOCKWISE": SpinPattern,
            "BLUE_COUNTERCLOCKWISE": SpinPattern,
            "CYAN_CLOCKWISE": SpinPattern,
            "CYAN_COUNTERCLOCKWISE": SpinPattern,
            "COUNTDOWN": CountdownPattern
        }

        self.current_pattern = None

    def run(self):
        self.strip = Adafruit_NeoPixel(8, self.neopixel_pin, 800000, 10, False,
                                       255, 0)
        self.strip.begin()
        self.change_pattern("BLANK")
        self.mqtt_client.loop_forever()

    def change_pattern(self, pattern_name):
        if self.current_pattern is not None:
            self.current_pattern.stop()

        if pattern_name in self.pattern_classes:
            self.current_pattern = self.pattern_classes[pattern_name](
                self, pattern_name, self.config)
            self.current_pattern.start()
        else:
            self.current_pattern = None

    def on_message(self, client, userdata, message):
        logger = logging.getLogger(__name__)
        msg = message.payload.decode('utf-8')
        logger.debug(msg)
        self.change_pattern(msg)

    def writeSPIData(self, ledList):
        led_index = 0
        for l in ledList:
            self.strip.setPixelColorRGB(led_index, l[1], l[0], l[2])
            led_index += 1

        self.strip.show()
Example #6
0
def main():
    # 根据agent_id点亮不同位置的灯区分树莓派 1 2 3
    print('suceess0:the number of this pi is %d:', agent_id)
    strip = Adafruit_NeoPixel(32, 18, 800000, 10, False, 10)
    strip.begin()
    strip.setPixelColor(agent_id, Color(255, 0, 0))
    strip.show()

    print('suceess1:begin thread')
    # 创建新线程
    thread1 = myThread1(1, "Thread-1", 1)
    thread2 = myThread1(2, "Thread-2", 2)

    # 开启线程
    thread1.start()
    thread2.start()
Example #7
0
class LED():
    def __init__(self):
        # Create NeoPixel object with appropriate configuration.
        self.strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ,
                                       LED_DMA, LED_INVERT, LED_BRIGHTNESS,
                                       LED_CHANNEL)
        # Intialize the library (must be called once before other functions).
        self.strip.begin()

    def colorWipe(self, rgb, wait_ms=50):
        """Wipe color across display a pixel at a time.
        :param rgb: color
        :type rgb: tuple(int, int, int) 
        """
        color = Color(*rgb)
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(i, color)
            self.strip.show()
            time.sleep(wait_ms / 10000.0)
Example #8
0
class LedStrip:

    def __init__(self):
        # LED strip configuration:
        self._LED_COUNT = 4  # Number of LED pixels.
        self._LED_PIN = 18  # GPIO pin connected to the pixels (must support PWM!).
        self._LED_FREQ_HZ = 800000  # LED signal frequency in hertz (usually 800khz)
        self._LED_DMA = 5  # DMA channel to use for generating signal (try 5)
        self._LED_BRIGHTNESS = 255  # 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
        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()
        self.switchOffStrip()

    def setPixelColourRgb(self, position, red, green, blue):
        self._strip.setPixelColor(position, Color(red, green, blue))
        self._strip.show()

    def setStripBrightness(self, brightness):
        self._strip.setBrightness(brightness)

    def switchOffPixel(self, position):
        self._strip.setPixelColor(position, Color(0, 0, 0))
        self._strip.show()

    def switchOffStrip(self):
        for n in range(0, self._LED_COUNT):
            self._strip.setPixelColor(n, Color(0, 0, 0))
        self._strip.show()
Example #9
0
class LedControl:
    def __init__(self):
        # Create NeoPixel object with appropriate configuration.
        self.strip = Adafruit_NeoPixel(
            LED_COUNT,
            LED_PIN,
            LED_FREQ_HZ,
            LED_DMA,
            LED_INVERT,
            LED_BRIGHTNESS,
            LED_CHANNEL,
        )
        # Intialize the library (must be called once before other functions).
        self.strip.begin()

    def color_wipe(self, color):
        """Wipe color across display a pixel at a time."""
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(i, color)
        self.strip.show()

    def transition_to_white(self, steps=18000, timestep=100):
        """
        Transition all leds to white
        :param steps: number of steps in transition
        :param timestep: time that one step takes in ms
        """
        final_color = np.array([255, 255, 255])
        start_color = np.array([0, 0, 0])
        color_delta = final_color - start_color
        for i in range(steps):
            # create linear i in range 0 to 100
            lin_range = i / (steps - 1) * 100
            # create exponential range from 1 to exp(100)
            log_range = np.exp(lin_range)
            # create exponential range from 0 to 1
            log_range = (log_range - 1) / (np.exp(100) - 1)
            color = start_color + color_delta * lin_range / 100  # log_range
            self.color_wipe(Color(int(color[0]), int(color[1]), int(color[2])))
            time.sleep(timestep / 1000)
Example #10
0
class Leds:
    def __init__(self, count, pin=21, br=100):
        """
        LEDs
        """
        self.LED_COUNT = count
        LED_PIN = pin  # GPIO пин, к которому вы подсоединяете светодиодную ленту
        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 = br  # 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

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

    def setPixelsColor(self, color):
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(i, color)
        self.strip.show()

    def setPixelColor(self, color):
        self.strip.setPixelColor(i, color)
        self.strip.show()

    def colorWipe(self, color, wait_ms=50):
        """Wipe color across display a pixel at a time."""
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(i, color)
            self.strip.show()
            time.sleep(wait_ms / 1000.0)
Example #11
0
class StripManager:

    @staticmethod
    def default():
        led_count = 159  # Number of LED pixels.
        led_pin = 18  # 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
        return StripManager(led_count, led_pin, led_freq_hz, led_dma, led_invert, led_brightness, led_channel)

    def __init__(self, led_count, led_pin, led_freq_hz, led_dma, led_invert, led_brightness, led_channel):
        self.strip = Adafruit_NeoPixel(led_count, led_pin, led_freq_hz, led_dma, led_invert, led_brightness,
                                       led_channel)
        self.strip.begin()

    def solid_color(self, r, g, b):
        self.strip.setBrightness(255)
        for i in range(0, self.strip.numPixels()):
            self.strip.setPixelColor(i, Color(r, g, b))
            self.strip.show()

    def alert(self, r, g, b, wait_ms=50, iterations=10):
        for j in range(iterations):
            for q in range(3):
                for i in range(0, self.strip.numPixels(), 3):
                    self.strip.setPixelColor(i + q, Color(r, g, b))
                self.strip.show()
                time.sleep(wait_ms / 1000.0)
                for i in range(0, self.strip.numPixels(), 3):
                    self.strip.setPixelColor(i + q, 0)

    def clear(self):
        self.solid_color(0, 0, 0)

    def orange(self):
        self.solid_color(255, 64, 0)
Example #12
0
def main():
    # 根据agent_id点亮不同位置的灯区分树莓派 1 2 3
    print('suceess0:the number of this pi is %d:',agent_id)
    strip = Adafruit_NeoPixel(32, 18, 800000, 10, False, 10)
    strip.begin()
    strip.setPixelColor(agent_id, Color(255, 0, 0))
    strip.show()
    
#     context = zmq.Context()
#     publisher = context.socket(zmq.PUB)
#     publisher.connect("tcp://%s:5556" % broker_ip)

#     subscriber = context.socket(zmq.SUB)
#     subscriber.connect("tcp://%s:5555" % broker_ip)
#     subscriber.setsockopt_string(zmq.SUBSCRIBE, str(agent_id))
    print('suceess1:begin thread')
    # 创建新线程
    thread1 = myThread1(1, "Thread-1", 1)
    thread2 = myThread1(2, "Thread-2", 2)
 
    # 开启线程
    thread1.start()
    thread2.start()
Example #13
0
class LEDChanger:
    '''
    Used to change the color of the LEDs.
    '''
    def __init__(self, config):
        '''
        Init params:
        config -- Dictionary containing a 'color-codes' key that points to a list made of that that many elements as there are colors.
            Each element of this list contains that many elements as many LEDs there are to control. Each of that list represents an RGB color.
            Also, 'color names' key is present (strings that are to be recognized by GiggleBotQAValidation class)
            and the GPIO port to control the NeoPixel LEDs.

        config must have this form:
        {
            'color-codes': [[(255, 0, 0)] * 9, [(0, 255, 0)] * 9, [(0, 0, 255)] * 9],
            'color-names': ['red', 'green', 'blue'],
            'gpio-port': 12
        }
        '''
        self._colors = config['color-codes']
        self._color_names = config['color-names']
        self._no_leds = len(self._colors[0])
        self._counter = 0
        self._port = config['gpio-port']

        self.initialize()

    def initialize(self):
        '''
        Use this method to reinitialize the connection to the neopixels when an exception occurs.
        '''
        try:
            self._pixels = Adafruit_NeoPixel(self._no_leds, self._port, 800000,
                                             10, False, 255)
            self._pixels.begin()
            self._failed = False
        except Exception as error:
            self._failed = True

    def update(self):
        '''
        Returns a dictionary containing 2 keys:
        'leds': The color of all LEDs: can be one of those specified in the config parameter in the constructor.
        'id': An ever increasing counter used to identify frames.

        Can throw exceptions if something goes wrong. When it does, call `initialize` method to reinitialize the connection.
        '''
        leds_color = self._colors[self._counter % 3]
        for i in range(self._no_leds):
            color = leds_color[i]
            self._pixels.setPixelColor(i, Color(color[0], color[1], color[2]))
        self._pixels.show()

        self._state = {
            'leds': self._color_names[self._counter % 3],
            'id': self._counter
        }
        self._counter += 1

        return self._state

    def failed(self):
        return self._failed

    def reset(self):
        self._failed = False
Example #14
0
# LED strip configuration:
LED_COUNT = 4  # 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)
LED_CHANNEL = 0

# Create NeoPixel object with appropriate configuration.
strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT,
                          LED_BRIGHTNESS, LED_CHANNEL)
# Intialize the library (must be called once before other functions).
strip.begin()
strip.show()

rgb = 0
light_type = 'static'  #'static':静态 'breath':呼吸 'flash':闪烁


#访问文件根目录
@get("/")
def index():
    global rgb, light_type
    rgb = 0xffffff
    light_type = 'static'
    return static_file('index.html', './')


#网页上的静态文件需要做传输处理
Example #15
0
class RGB(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.thread_name = "RGB_LIGHT"
        self.strip = Adafruit_NeoPixel(configs.LED_COUNT, configs.LED_PIN,
                                       configs.LED_FREQ_HZ, configs.LED_DMA,
                                       configs.LED_INVERT,
                                       configs.LED_BRIGHTNESS)
        self.strip.begin()
        init_color = Color(0, 0, 0)
        self.led_colors = [init_color for i in range(configs.LED_COUNT)]
        # 预警返回值,如果为1,则需要颜色预警
        self.remind_type = 0
        my_print(self, 'init done!')

    def run(self) -> None:
        while True:
            if self.remind_type:
                # 先清除颜色
                self.colorWipe(Color(0, 0, 0), 0)
                self.breath_chase()
                self.remind_type = 0
            self.rainbowCycle()

    #功能一-逐个变色-
    # colorWipe(self.strip, Color(255, 0, 0))  # Red wipe
    # 所有灯逐个变成红色
    def colorWipe(self, color, wait_ms=50):
        """Wipe color across display a pixel at a time."""
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(i, color)
            self.strip.show()
            time.sleep(wait_ms / 1000.0)

    # 呼吸闪烁
    def breath_chase(self, wait_ms=3):
        for i in range(0, 255, 3):
            now_color = Color(i, 0, 0)
            # 所有灯珠设置一遍
            self.colorWipe(now_color, 0)
            # 延时
            time.sleep(wait_ms / 1000.0)
        for i in range(255, 0, -3):
            now_color = Color(i, 0, 0)
            self.colorWipe(now_color, 0)
            time.sleep(wait_ms / 1000.0)

    # 渐变至某个颜色
    def gradient_change(self, color):
        pass

    # 白色交替闪烁
    def theaterChase(self, color, 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.strip.numPixels(), 3):
                    self.strip.setPixelColor(i + q, color)
                self.strip.show()
                time.sleep(wait_ms / 1000.0)
                for i in range(0, self.strip.numPixels(), 3):
                    self.strip.setPixelColor(i + q, 0)

    # 支撑函数
    def wheel(self, pos):
        """Generate rainbow colors across 0-255 positions."""
        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 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.strip.numPixels()):
                self.strip.setPixelColor(i, self.wheel((i + j) & 255))
            self.strip.show()
            time.sleep(wait_ms / 1000.0)

    #功能四-彩虹色每一个灯各自柔和渐变-每个灯颜色同一时间不同
    def rainbowCycle(self, wait_ms=20, iterations=5):
        """Draw rainbow that uniformly distributes itself across all pixels."""
        for j in range(256 * iterations):
            # 如果颜色渐变的时候预警了,推出循环
            if self.remind_type == 1:
                break
            for i in range(self.strip.numPixels()):
                self.strip.setPixelColor(
                    i,
                    self.wheel((int(i * 256 / self.strip.numPixels()) + j)
                               & 255))
            self.strip.show()
            time.sleep(wait_ms / 1000.0)

    #功能五-彩虹色统一闪烁流动变色-每个灯颜色同一时间相同
    def theaterChaseRainbow(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.strip.numPixels(), 3):
                    self.strip.setPixelColor(i + q, self.wheel((i + j) % 255))
                self.strip.show()
                time.sleep(wait_ms / 1000.0)
                for i in range(0, self.strip.numPixels(), 3):
                    self.strip.setPixelColor(i + q, 0)

    def test(self):
        print('Color wipe animations.')
        self.colorWipe(Color(155, 0, 0))  # Red wipe
        self.colorWipe(Color(0, 255, 0))  # Blue wipe
        self.colorWipe(Color(0, 0, 255))  # Green wipe
        print('Theater chase animations.')
        self.theaterChase(Color(127, 127, 127))  # White theater chase
        self.theaterChase(Color(127, 0, 0))  # Red theater chase
        self.theaterChase(Color(0, 0, 127))  # Blue theater chase
        print('Rainbow animations.')
        self.rainbow()
        self.rainbowCycle()
        self.theaterChaseRainbow()
Example #16
0
class LedController(Actuator):
    """Implementation for the Neopixel Programmable RGB LEDS. Extends 
    :class:`Actuator`.
    
    It use's rpi_ws281x library.

    Args:
        led_count (int): Number of leds.
        led_pin (int): GPIO pin connected to the pixels.
        led_freq_hz (int): LED signal frequency in hertz (usually 800khz)
        led_brightness (int): Set to 0 for darkest and 255 for brightest
        led_dma (int): DMA channel to use for generating signal.
            Defaults to :data:`10`.
        led_invert (boolean): True to invert the signal 
            (when using NPN transistor level shift). Defaults to :data:`False`.
        led_channel (int): Set to '1' for GPIOs 13, 19, 41, 45 or 53. Defaults
            to :data:`0`.
        led_strip: Strip type and colour ordering. Defaults to 
            :data:`ws.WS2811_STRIP_RGB`.
    """
    def __init__(self,
                 led_count,
                 led_pin,
                 led_freq_hz,
                 led_brightness,
                 led_dma=10,
                 led_invert=False,
                 led_channel=0,
                 led_strip=ws.WS2811_STRIP_RGB,
                 name=""):
        """Constructor"""

        self._led_count = led_count
        self._led_pin = led_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._led_strip = led_strip

        # Set the id of the actuator
        super(LedController, self).__init__(name)

        self.start()

    @property
    def led_count(self):
        """Number of leds."""
        return self._led_count

    @led_count.setter
    def led_count(self, x):
        self._led_count = x

    @property
    def led_pin(self):
        """GPIO pin connected to the pixels."""
        return self._led_pin

    @led_pin.setter
    def led_pin(self, x):
        self._led_pin = x

    @property
    def led_freq_hz(self):
        """LED signal frequency in hertz."""
        return self._led_freq_hz

    @led_freq_hz.setter
    def led_freq_hz(self, x):
        self._led_freq_hz = x

    @property
    def led_brightness(self):
        """Set to 0 for darkest and 255 for brightest."""
        return self._led_brightness

    @led_brightness.setter
    def led_brightness(self, x):
        self._led_brightness = x

    @property
    def led_dma(self):
        """DMA channel to use for generating signal."""
        return self._led_dma

    @led_dma.setter
    def led_dma(self, x):
        self._led_dma = x

    @property
    def led_invert(self):
        """True to invert the signal."""
        return self._led_invert

    @led_invert.setter
    def led_invert(self, x):
        self._led_invert = x

    @property
    def led_channel(self):
        """Set to '1' for GPIOs 13, 19, 41, 45 or 53."""
        return self._led_channel

    @led_channel.setter
    def led_channel(self, x):
        self._led_channel = x

    @property
    def led_strip(self):
        """Strip type and color ordering."""
        return self._led_strip

    @led_strip.setter
    def led_strip(self, x):
        self._led_strip = x

    def start(self):
        """Initialize hardware and os resources."""
        # Create NeoPixel object with appropriate configuration.
        self.strip = Adafruit_NeoPixel(self.led_count, self.led_pin,
                                       int(self.led_freq_hz), self.led_dma,
                                       self.led_invert, self.led_brightness,
                                       self.led_channel, self.led_strip)

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

    def stop(self):
        """Free hardware and os resources."""
        # Turn-off led strip
        self.close()

    def write(self, data, wait_ms=50, wipe=False):
        """Write to the leds.
        
        Args:
            data: A list of lists of which each list corresponds to each led 
                and the values are [red, green, blue, brightness].
            wait_ms (int): Optional argument that has to be set when wipe is 
                :data:`True`. Defaults to :data:`50`.
            wipe: Flag for writting to all leds at once.
        """

        if wipe:
            self._color_wipe(data[0][:3],
                             wait_ms=wait_ms,
                             brightness=data[0][3])
        else:
            for (i, led) in enumerate(data):
                self.strip.setPixelColor(i, Color(led[1], led[0], led[2]))
                self.strip.setBrightness(led[3])
                self.strip.show()
                time.sleep(0.1)

    def close(self):
        """Free hardware and os resources."""

        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(i, Color(0, 0, 0))
            self.strip.show()

        self.strip._cleanup()
        del self.strip

    def _color_wipe(self, rgb_color=[0, 0, 255], wait_ms=50, brightness=60):
        """Wipe color across display a pixel at a time."""
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(
                i, Color(rgb_color[1], rgb_color[0], rgb_color[2]))
            self.strip.setBrightness(brightness)
            self.strip.show()
            time.sleep(wait_ms / 1000.0)
Example #17
0
strip1 = Adafruit_NeoPixel(LED_1_COUNT, LED_1_PIN, 800000, 5, False,
                           LED_1_BRIGHTNESS, 0, ws.WS2811_STRIP_GRB)
strip1.begin()

strip2 = Adafruit_NeoPixel(LED_2_COUNT, LED_2_PIN, 800000, 6, False,
                           LED_2_BRIGHTNESS, 0, ws.WS2811_STRIP_GRB)
strip2.begin()

# strip3 = Adafruit_NeoPixel(LED_3_COUNT, LED_3_PIN, 800000, 7, False, LED_2_BRIGHTNESS, 0, ws.WS2811_STRIP_GRB)
# strip3.begin()

if __name__ == '__main__':
    while True:
        for i in range(strip1.numPixels()):
            strip1.setPixelColor(i, COLOR.RED)
        strip1.show()

        for i in range(strip2.numPixels()):
            strip2.setPixelColor(i, COLOR.GREEN)
        strip2.show()

        # for i in range(strip3.numPixels()):
        # 	strip3.setPixelColor(i, COLOR.BLUE)
        # strip3.show()

        time.sleep(1)

        for i in range(strip1.numPixels()):
            strip1.setPixelColor(i, COLOR.GREEN)
        strip1.show()
Example #18
0
class Led_Controller_Manager:
    def __init__(self,
                 led_count=60,
                 led_pin=18,
                 sections={'default': range(0, 60)},
                 virtual_sections={}):
        """Creates a new Led_Controller Manager.
        led_count: Total number of LED pixels physically connected to this Pi
        led_pin: GPIO pin connected to the pixels (must support PWM!)
        sections: The named led sections that can be controlled
        virtual_sections: The names of the sections that are not connected to this device
        and their respective controller modules.
        """
        if led_count > 0:
            from rpi_ws281x import Adafruit_NeoPixel, WS2812_STRIP
            LED_STRIP = WS2812_STRIP  #Uses GBR instead of RGB
            self.ws2812 = Adafruit_NeoPixel(led_count, led_pin, LED_FREQ_HZ,
                                            LED_DMA, LED_INVERT,
                                            LED_BRIGHTNESS, LED_CHANNEL,
                                            LED_STRIP)
            self.ws2812.begin()
        self.controllers = []
        self.sections = sections
        self.section_ordered = sorted(self.sections,
                                      key=lambda e: self.sections[e][-1])
        self.virtual_sections = virtual_sections
        #Number of leds in all sections, local and virtual
        self.total_leds = max(r[-1] + 1 for r in self.sections.values())
        #A mapping from absolute index to (local index, controller)
        #"Local pixels" will be formatted as (index, self.ws2182)
        self.pixel_locations = [-1] * self.total_leds
        local_index = 0
        for section_name in self.section_ordered:
            if section_name in virtual_sections:
                virtual_index = 0
                for i in self.sections[section_name]:
                    self.pixel_locations[i] = (
                        virtual_index, self.virtual_sections[section_name])
                    virtual_index += 1
            else:
                for i in self.sections[section_name]:
                    self.pixel_locations[i] = (local_index, self.ws2812)
                    local_index += 1

    # Creates a new Led_Controller for the sections, and removes intersecting sections from other controllers
    def create_controller(self, sections):
        controller = Led_Controller(self)
        controller.set_sections(sections)
        for c in self.controllers:
            if any(s in sections for s in c.active_sections):
                c.set_sections(
                    [s for s in c.active_sections if s not in sections])
        self.controllers.append(controller)
        # Remove any empty controllers
        self.controllers = [c for c in self.controllers if c.num_leds != 0]
        return controller

    def get_controllers(self):
        return self.controllers

    def show(self):
        """Pushes the led array to the actual lights"""
        # TODO lock self.controllers while reading. Not thread safe
        for controller in self.controllers:
            controller.render()

        if len(self.sections) > len(self.virtual_sections):
            self.ws2812.show()
        for vr in self.virtual_sections:
            self.virtual_sections[vr].show()

    def get_pixels(self):
        r = []
        for c in self.controllers:
            logger.info(c)
            for p in c.get_pixels():
                r += [p]
        logger.info(r)
        return r
Example #19
0
class LedService:

    # Number of LED pixels.
    LED_COUNT = 16

    # GPIO pin connected to the pixels (18 uses PWM!).
    LED_PIN = 12

    # LED signal frequency in hertz (usually 800khz)
    LED_FREQ_HZ = 800000

    # DMA channel to use for generating signal (try 10)
    LED_DMA = 10

    # Set to 0 for darkest and 255 for brightest
    LED_BRIGHTNESS = 255

    # True to invert the signal (when using NPN transistor level shift)
    LED_INVERT = False

    # set to '1' for GPIOs 13, 19, 41, 45 or 53
    LED_CHANNEL = 0

    leds = []
    breath = []
    changed = False
    strip = None
    update_frequency = 50

    is_breathing = False
    breath_time_factor = 8

    thread = None
    running = True

    def __init__(self, command_controller):
        self.command_controller = command_controller
        self.create_commands()
        if os.name != 'nt':
            self.init_strip()
        self.init_led_states()
        signal('exit').connect(self.exit)
        signal('diag').send(self, name='led_service', state='starting')

    def create_commands(self):
        parser = self.command_controller.create_command(
            'led',
            'Control the LED',
            self.handle_led_command
        )
        parser.add_argument('--id', type=int, default=-1, help='The change affects to the given led')
        parser.add_argument('--red', type=int, help='Changes the red value')
        parser.add_argument('--green', type=int, help='Changes the green value')
        parser.add_argument('--blue', type=int, help='Changes the blue value')
        parser.add_argument('--is-breathing', type=self.str_to_bool, help='Breathing')
        parser.add_argument('--breath_time_factor', type=int, help='Sets the breath time factor')

    def str_to_bool(self, value):
        if isinstance(value, bool):
            return value
        if value.lower() in {'false', 'f', '0', 'no', 'n', 'off'}:
            return False
        elif value.lower() in {'true', 't', '1', 'yes', 'y', 'on'}:
            return True
        raise ValueError(f'{value} is not a valid boolean value')

    def init_led_states(self):
        self.breath.append([])
        self.breath.append([])
        for id in range(self.LED_COUNT):
            self.leds.append({"changed": True, "r": 0, "g": 0, "b": 0})
            self.breath[0].append({"r": 255, "g": 35, "b": 70})
            self.breath[1].append({"r": 35, "g": 70, "b": 255})

    def init_strip(self):
        # Create NeoPixel object with appropriate configuration.
        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
        )
        # Initialize the library (must be called once before other functions)
        self.strip.begin()

    def create_thread(self):
        self.thread = threading.Thread(target=self.run)

    def start(self):
        self.thread.start()

    def join(self):
        self.thread.join()

    def step(self):
        changed = False
        if self.is_breathing:
            self.calc_breath()
        for id in range(self.LED_COUNT):
            led = self.leds[id]
            if led['changed']:
                if self.strip is not None:
                    self.strip.setPixelColor(
                        id,
                        Color(led['r'], led['g'], led['b'])
                    )
                changed = True
                led['changed'] = False
        if changed:
            if self.strip is not None:
                self.strip.show()
            else:
                print('[led_service] updated')

    def run(self):
        print('[led_service] started')
        signal('diag').send(self, name='led_service', state='started')
        while self.running:
            self.step()
            time.sleep(1 / self.update_frequency)
        signal('diag').send(self, name='led_service', state='stopping')
        print('[led_service] stopping')

    def exit(self, args=None):
        print('[led_service] exiting...')
        self.running = False

    def set_update_frequency(self, update_frequency):
        self.update_frequency = update_frequency

    def set_led_color(self, id, r=0, g=0, b=0):
        self.leds[id] = {"changed": True, "r": r, "g": g, "b": b}

    def set_all_led_colors(self, r=0, g=0, b=0):
        for id in range(self.LED_COUNT):
            self.set_led_color(id, r, g, b)

    def color(self, id=-1, r=0, g=0, b=0):
        if id >= 0:
            self.set_led_color(r, g, b)
        else:
            self.set_all_led_colors(r, g, b)

    def black(self, id=-1):
        self.color(id)

    def white(self, id=-1):
        self.color(id, 255, 255, 255)

    def blue(self, id=-1):
        self.color(id, 255, 0, 0)

    def sine_between(self, min, max, t):
        _min = min
        _max = max
        if min > max:
            _min = max
            _max = min
        halfRange = (_max - _min) / 2.0
        return int(round(_min + halfRange + sin(t) * halfRange))

    def calc_breath(self):
        t = time.time() * self.breath_time_factor
        for id in range(self.LED_COUNT):
            led = self.leds[id]
            breath_min = self.breath[0][id]
            breath_max = self.breath[1][id]
            led['r'] = self.sine_between(breath_min['r'], breath_max['r'], t)
            led['g'] = self.sine_between(breath_min['g'], breath_max['g'], t)
            led['b'] = self.sine_between(breath_min['b'], breath_max['b'], t)
            led['changed'] = True
            print('[breath] %3d %3d %3d' %(led['r'], led['r'], led['r']))

    def handle_led_command(self, args=None):
        print(args)
        if args.red is not None or args.green is not None or args.green is not None:
            if args.id >= 0:
                if args.red is not None and 0 <= args.red <= 255:
                    self.leds[args.id]['r'] = args.red
                if args.green is not None and 0 <= args.green <= 255:
                    self.leds[args.id]['g'] = args.green
                if args.blue is not None and 0 <= args.blue <= 255:
                    self.leds[args.id]['b'] = args.blue
                self.leds[args.id]['changed'] = True
            else:
                for id in range(self.LED_COUNT):
                    if args.red is not None and 0 <= args.red <= 255:
                        self.leds[id]['r'] = args.red
                    if args.green is not None and 0 <= args.green <= 255:
                        self.leds[id]['g'] = args.green
                    if args.blue is not None and 0 <= args.blue <= 255:
                        self.leds[id]['b'] = args.blue
                    self.leds[id]['changed'] = True
        if args.is_breathing is not None:
            self.is_breathing = args.is_breathing
        if args.breath_time_factor is not None:
            self.breath_time_factor = args.breath_time_factor
Example #20
0
# Compare current weather to the rain shower list

    if test >= rainshowerlo and test <= rainshowerhi:
        wh.cloud("start")
        wh.raining("start")
        wh.rainbow("start")

# Compare current weather to the snow list

    if test >= snowlo and test <= snowhi:
        wh.cloud("start")
        panel.setPixelColor(0, Color(255, 255, 255))
        panel.setPixelColor(2, Color(255, 255, 255))
        panel.setPixelColor(4, Color(255, 255, 255))
        panel.setPixelColor(6, Color(255, 255, 255))
        panel.show()

# Compare current weather to the snow shower list

    if test >= snowshowerlo and test <= snowshowerhi:
        wh.cloud("start")
        panel.setPixelColor(0, Color(255, 255, 255))
        panel.setPixelColor(2, Color(255, 255, 255))
        panel.setPixelColor(4, Color(255, 255, 255))
        panel.setPixelColor(6, Color(255, 255, 255))
        panel.show()
        wh.rainbow("start")

# Compare current weather to the thunderstorm list

    if test >= tstormlo and test <= tstormhi:
Example #21
0
class PiStripLed(piIotNode.PiIotNode):
    """ encapsulates the RGB led strip using ws281x """
    def __init__(self,
                 name,
                 parent,
                 ledCount,
                 ledPin,
                 freq=800000,
                 dmaChannel=10,
                 invert=False,
                 brightness=255,
                 ledChannel=0,
                 debug=False):
        """ construct a strip led """
        super(PiStripLed, self).__init__(name, parent)
        self.debug = debug
        # Create NeoPixel object with appropriate configuration.
        self.strip = Adafruit_NeoPixel(ledCount, ledPin, freq, dmaChannel,
                                       invert, brightness, ledChannel)
        # Intialize the library (must be called once before other functions).
        self.strip.begin()

    def setPixel(self, i, red, green, blue):
        """ set color for a single pixel with red, green, blue values"""
        self.setPixelColor(i, Color(red, green, blue))

    def setPixelRGB(self, i, rgb):
        """ set color for a single pixel with RGB object """
        red, green, blue = rgb.toRGBList()
        self.setPixelColor(i, Color(int(red), int(green), int(blue)))

    def setPixelRGBStr(self, i, rgbStr):
        """ set color for a single pixel with RGB string """
        red, green, blue = rgbStr.split(',')
        self.setPixelColor(i, Color(int(red), int(green), int(blue)))

    def setPixelColor(self, i, color):
        """ set color for a single pixel with rpi_ws281x Color object """
        self.strip.setPixelColor(i, color)
        self.strip.show()

    def setAllPixels(self, red, green, blue, delay_ms=5):
        """ set color across all pixels with delay time between pixel."""
        self.setAllPixelsColor(Color(red, green, blue), delay_ms)

    def setAllPixelsRGB(self, rgb, delay_ms=5):
        """ set color across all pixels with delay time between pixel."""
        red, green, blue = rgb.toRGBList()
        self.setAllPixelsColor(Color(red, green, blue), delay_ms)

    def setAllPixelsRGBStr(self, rgbStr, delay_ms=5):
        """ set color across all pixels with delay time between pixel."""
        red, green, blue = rgbStr.split(',')
        self.setAllPixelsColor(Color(int(red), int(green), int(blue)),
                               delay_ms)

    def setAllPixelsColor(self, color, delay_ms=5):
        """ set color across all pixels with delay time between pixel."""
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(i, color)
            self.strip.show()
            time.sleep(delay_ms / 1000.0)

    @staticmethod
    def wheel(pos):
        """ generate rainbow colors across 0-255 positions """
        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 rainbowCycle(self, delay_ms=20, iterations=5):
        """ Draw rainbow that uniformly distributes itself across all pixels """
        self._debugInfo('start rainbowCycle')
        for j in range(256 * iterations):
            for i in range(self.strip.numPixels()):
                self.strip.setPixelColor(
                    i,
                    PiStripLed.wheel((int(i * 256 / self.strip.numPixels()) +
                                      j) & 255))
            self.strip.show()
            time.sleep(delay_ms / 1000.0)
        self._debugInfo('end rainbowCycle')

    def theaterChaseRainbow(self, delay_ms=50):
        """Rainbow movie theater light style chaser animation."""
        self._debugInfo('start theaterChaseRainbow')
        for j in range(256):
            for q in range(3):
                for i in range(0, self.strip.numPixels(), 3):
                    self.strip.setPixelColor(i + q,
                                             PiStripLed.wheel((i + j) % 255))
                self.strip.show()
                time.sleep(delay_ms / 1000.0)
                for i in range(0, self.strip.numPixels(), 3):
                    self.strip.setPixelColor(i + q, 0)
        self._debugInfo('end theaterChaseRainbow')

    def _debugInfo(self, msg):
        """ print debug info when debug is enabled """
        if self.debug:
            print(msg)
Example #22
0
class Animator:
    def __init__(self):
        self._kill_previous_process()
        self._animations_dir = os.path.join(os.getcwd(), 'animations')
        self._frame_handlers = {
            ord('P'): self._on_pframe,
            ord('I'): self._on_iframe,
            ord('D'): self._on_dframe,
            ord('F'): self._on_fframe
        }
        settings = self._load_settings()
        brightness = settings['brightness'] * 255 // 50
        self._strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ,
                                        LED_DMA, LED_INVERT, brightness,
                                        LED_CHANNEL)
        self._strip.begin()
        self._strip.setBrightness(50)
        self._animation = None

    def _load_settings(self):
        with open('settings.yaml') as fh:
            settings = yaml.load(fh, Loader=yaml.FullLoader)
            return settings

    def _get_previous_process(self):
        cur_pid = psutil.Process().pid
        for proc in psutil.process_iter(['pid', 'name', 'cmdline']):
            if proc.pid == cur_pid or proc.name(
            ) != 'python' or 'animate.py' not in proc.cmdline():
                continue
            return proc
        return None

    def _kill_previous_process(self):
        proc = self._get_previous_process()
        if proc:
            proc.terminate()
            psutil.wait_procs([proc])

    def _on_pframe(self, frame):
        for item in frame.data:
            clr = self._animation.palette[item.palette_index]
            color = Color(clr.g, clr.r, clr.b)
            index = TOPOLOGY[EPX_TOPOLOGY[item.pixel_index]]
            if index > 0:
                self._strip.setPixelColor(index, color)
        return

    def _on_iframe(self, frame):
        for pixel_index, palette_index in enumerate(frame.data):
            clr = self._animation.palette[palette_index]
            color = Color(clr.g, clr.r, clr.b)
            index = TOPOLOGY[EPX_TOPOLOGY[pixel_index]]
            if index > 0:
                self._strip.setPixelColor(index, color)
        return

    def _on_dframe(self, frame):
        sleep(frame.delay / 1000)

    def _on_fframe(self, frame):
        # TODO: implement proper fading
        sleep(frame.delay)

    def _show_frame(self, frame):
        handler = self._frame_handlers[frame.type]
        handler(frame)
        self._strip.show()

    def _run(self):
        if self._animation == None:
            return
        self.clear()
        loop_count = max(self._animation.loop_count, 1)
        try:
            for i in range(loop_count):
                for frame in self._animation.data:
                    self._show_frame(frame)
                    sleep(0.1)
        except KeyboardInterrupt:
            pass
        self.clear()

    def _load_animations(self):
        files = [f for f in os.listdir(self._animations_dir)]
        animations = []
        for file in files:
            filepath = os.path.join(self._animations_dir, file)
            animation = Animation.load(filepath)
            animations.append(animation)
        return animations

    def _find_animation_by_id(self, id):
        animations = self._load_animations()
        animation = next((x for x in animations if x.id == id), None)
        return animation

    def _find_animation_by_name(self, name):
        animations = self._load_animations()
        animation = next((x for x in animations if x.name == name), None)
        return animation

    def clear(self):
        color = Color(0, 0, 0)
        for i in range(LED_COUNT):
            self._strip.setPixelColor(i, color)
        self._strip.show()

    def play(self, filename):
        self._animation = Animation.load(filename)
        self._run()

    def play_by_id(self, id):
        self._animation = self._find_animation_by_id(id)
        self._run()

    def play_by_name(self, name):
        self._animation = self._find_animation_by_name(name)
        self._run()

    def restart(self):
        proc = self._get_previous_process()
        if not proc:
            return
        args = ['sudo', proc.name()]
        args.extend(proc.cmdline())
        proc.terminate()
        psutil.wait_procs([proc])
        subprocess.run(args)

    def play_all(self, randomly, forever):
        animations = self._load_animations()
        if randomly:
            random.shuffle(animations)

        while True:
            for animation in animations:
                print(f'{animation.name}')
                self._animation = animation
                self._run()

            if not forever:
                break

            if randomly:
                random.shuffle(animations)
Example #23
0
class PiWS281X(DriverBase):
    """
    Driver for controlling WS281X LEDs via the rpi_ws281x C-extension.
    Only supported on the Raspberry Pi 2, 3, and Zero

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

    Install rpi_ws281x with the following shell commands:

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

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

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

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

    :param int gpio: GPIO pin to output to. Typically 18 or 13
    :param int ledFreqHz: WS2812B base data frequency in Hz. Only change to
        400000 if using very old WS218B LEDs
    :param int ledDma: DMA channel to use for generating signal
                       (between 1 and 14)
    :param bool ledInvert: True to invert the signal
                       (when using NPN transistor level shift)
    """

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

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

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

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

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

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

        self._strip.show()
Example #24
0
class PiCamera(Camera):
    """
    Adapted from PyImageSearch
    https://www.pyimagesearch.com/2015/03/30/accessing-the-raspberry-pi-camera-with-opencv-and-python/
    """

    def __init__(self, window_name="PiCamera", algorithm=None):
        # Ensure object is created in RPi
        if not self.can_run():
            raise RuntimeError("PiCamera only allowed to be run via RPi. "
                               "Please use camera.Webcam for testing purposes.")

        from picamera.array import PiRGBArray
        from picamera import PiCamera

        # define camera
        self.camera = PiCamera()
        self.camera.resolution = (CAMERA_WIDTH, CAMERA_HEIGHT)
        self.camera.framerate = 30
        # grab reference to the raw camera capture
        self.rawCapture = PiRGBArray(self.camera)

        # setup lights
        from rpi_ws281x import Adafruit_NeoPixel, Color
        self.strip = Adafruit_NeoPixel(8, 18, 800000, 10, False, 255, 0)
        self.strip.begin()

        # Allow camera to warm up
        time.sleep(0.1)
        super().__init__(window_name, algorithm)

    def set_light_color(self, color):
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(i, color)
        self.strip.show()

    @staticmethod
    def can_run() -> bool:
        import os
        return os.uname()[4][:3] == "arm"

    def draw(self):
        self.camera.capture(self.rawCapture, format="bgr")
        image = self.rawCapture.array

    def process_video(self):
        # begin frame loop
        for frame in self.camera.capture_continuous(
                self.rawCapture,
                format="bgr",
                use_video_port=True
        ):
            # grab the raw numpy array representing the image
            image = frame.array

            image = self.algorithm.run(image).labelled_frame

            # show the frame
            cv2.imshow("Frame", image)
            key = cv2.waitKey(1) & 0xFF

            # clear the stream in preparation for the next frame
            self.rawCapture.truncate(0)

            # allow exit when 'q' is pressed
            if key == ord("q"):
                break

    def process_image(self):
        # capture image and get np array
        self.set_light_color(Color(255, 255, 255))
        self.camera.capture(self.rawCapture, format="bgr")
        image = self.rawCapture.array

        # process image
        image = self.algorithm(image).run().labelled_frame

        # display the image on screen
        cv2.imshow("Image", image)
        # also output with text and audio
        self.output_sound(image)

        # allow exit when any key is pressed
        print("Press any key to exit.")
        cv2.waitKey(0)

    def destroy(self):
        super().destroy()
        # clear lights
        self.set_light_color(Color(0, 0, 0))
Example #25
0
class HardwareHandler():
    """Class to handle LEDs and camera."""
    def __init__(self, imageQueue):

        self.imageQueue = imageQueue
        self.capture = False
        self.capture_thread = None
        self.cap = cv2.VideoCapture(constants.CAMERA_NUM - 1 + cv2.CAP_ANY)

        self.UV_LED = False
        self.COLOR_LED = False

        if not testMode:
            GPIO.setmode(GPIO.BOARD)
            GPIO.setup(constants.GPIO_UV_LED, GPIO.OUT)
            self.UV_LED_PWM = GPIO.PWM(constants.GPIO_UV_LED,
                                       800)  # channel=12 frequency=50Hz
            self.UV_LED_PWM.start(0)

            self.strip = Adafruit_NeoPixel(constants.COLOR_LED_NUM,
                                           constants.GPIO_COLOR_LED,
                                           dma=10)
            self.strip.begin()
            for n in range(constants.COLOR_LED_NUM):
                self.strip.setPixelColorRGB(
                    n, constants.settings["Color"]["LED_Red"],
                    constants.settings["Color"]["LED_Green"],
                    constants.settings["Color"]["LED_Blue"])

###################### LED ######################

    def switchUV_LED(self, val=None):
        """ switch UV LED or set to val"""
        if val is not None:
            self.UV_LED = val
        else:
            self.UV_LED = not self.UV_LED
        if not testMode:
            if self.UV_LED:
                self.UV_LED_PWM.ChangeDutyCycle(
                    constants.settings["UV"]["LED_Brigh"])
            else:
                self.UV_LED_PWM.ChangeDutyCycle(0)
        if self.UV_LED: logger.info("UV LED: On")
        else: logger.info("UV LED: Off")

    def switchCOLOR_LED(self, val=None):
        """ switch color LED or set to val
        :param bool val:"""
        if val is not None:
            self.COLOR_LED = val
        else:
            self.COLOR_LED = not self.COLOR_LED
        if not testMode:
            if self.COLOR_LED:
                self.strip.setBrightness(
                    constants.settings["Color"]["LED_Brigh"])
            else:
                self.strip.setBrightness(0)
            self.strip.show()
        if self.COLOR_LED: logger.info("Color LED: On")
        else: logger.info("Color LED: Off")

    def updateLEDColors(self):
        """ Update Color LED settings to constants.settings """
        if not testMode:
            for n in range(constants.COLOR_LED_NUM):
                self.strip.setPixelColorRGB(
                    n, constants.settings["Color"]["LED_Red"],
                    constants.settings["Color"]["LED_Green"],
                    constants.settings["Color"]["LED_Blue"])
            if self.COLOR_LED:
                self.strip.setBrightness(
                    constants.settings["Color"]["LED_Brigh"])
                self.strip.show()
        else:
            color = (constants.settings["Color"]["LED_Red"],
                     constants.settings["Color"]["LED_Green"],
                     constants.settings["Color"]["LED_Blue"],
                     constants.settings["Color"]["LED_Brigh"])
            logger.info(f"New LED Color: {color}. LED on: {self.COLOR_LED}")

    def updateLEDUV(self):
        """ Update UV LED settings to constants.settings """
        if not testMode:
            if self.UV_LED:
                self.UV_LED_PWM.ChangeDutyCycle(
                    constants.settings["UV"]["LED_Brigh"])
        else:
            logger.info(
                f"New UV LED Brightness: {constants.settings['UV']['LED_Brigh']}. LED on: {self.UV_LED}"
            )

###################### Camera ######################

    def startCapturing(self, mode="Color"):
        """ Start image capture & display """
        self.capture = True

        def grab_images(queue):
            self.setCaptureSettings(mode, "low")
            while self.capture:
                if self.cap.grab():
                    _, image = self.cap.retrieve(0)
                    if image is not None and queue.qsize() < 2:
                        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
                        image = cv2.resize(image,
                                           constants.DISPLAY_RESOLUTION[::-1],
                                           interpolation=cv2.INTER_CUBIC)
                        queue.put(image)
                    else:
                        time.sleep(constants.DISP_MSEC / 1000.0)
                else:
                    logger.fatal("Can't grab camera image")
                    logger.fatal("Using test image instead")
                    image = cv2.imread(constants.TEST_IMAGE_NAME)
                    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
                    image = cv2.resize(image,
                                       constants.DISPLAY_RESOLUTION[::-1],
                                       interpolation=cv2.INTER_CUBIC)
                    queue.put(image)
                    break

        self.capture_thread = threading.Thread(
            target=grab_images,
            args=(self.imageQueue, ))  # Thread to grab images
        self.capture_thread.start()

    def shootImage_fullResolution(self, mode="Color"):
        """Shoot single image with maximal camera resolution
        :return np.ndarray: image """
        self.setCaptureSettings(mode, "full")
        if self.cap.grab():
            _, fullImage = self.cap.retrieve(0)
        else:
            logger.fatal("Can't grab camera image")
            logger.fatal("Using test image instead")
            fullImage = cv2.imread(constants.TEST_IMAGE_NAME)

        fullImage = cv2.cvtColor(fullImage, cv2.COLOR_RGB2BGR)

        return fullImage

    def stopCapturing(self):
        """Stop if capturing."""
        if self.capture:
            self.capture = False
            self.capture_thread.join()
        self.imageQueue.queue.clear()

    def updateCaptureSettings(self, mode="Color"):
        """Stop capturing and start again with new settings"""
        self.stopCapturing()
        self.startCapturing(mode=mode)

    def __del__(self):
        if not testMode: GPIO.cleanup()

    def setCaptureSettings(self, LEDMmode, resolution):
        """Call cv2.VideoCapture and set settings."""

        #set fps dynamic to exposure
        fps = 20
        if constants.settings[LEDMmode]["exposureTime"] != 0:
            fps = int(
                max(
                    1,
                    min(20,
                        10000 / constants.settings[LEDMmode]["exposureTime"])))
        self.cap.set(cv2.CAP_PROP_FPS, fps)

        if resolution == "full":
            self.cap.set(cv2.CAP_PROP_FRAME_WIDTH,
                         constants.CAMERA_RESOLUTION[1])
            self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT,
                         constants.CAMERA_RESOLUTION[0])
        if resolution == "low":
            self.cap.set(cv2.CAP_PROP_FRAME_WIDTH,
                         constants.DISPLAY_RESOLUTION[1])
            self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT,
                         constants.DISPLAY_RESOLUTION[0])

        if not testMode:
            #set white balance
            subprocess.check_call(
                f"v4l2-ctl -d /dev/video0 -c white_balance_auto_preset=0 -c red_balance={constants.RED_GAIN} -c blue_balance={constants.BLUE_GAIN} -c exposure_dynamic_framerate=1 -c iso_sensitivity_auto=0 ",
                shell=True)
            #set exposure
            if constants.settings[LEDMmode][
                    "exposureTime"] == 0:  # exposureTime==0 -> auto
                subprocess.check_call(
                    "v4l2-ctl -d /dev/video0 -c white_balance_auto_preset=0 -c auto_exposure=0",
                    shell=True)
            else:
                subprocess.check_call(
                    f"v4l2-ctl -d /dev/video0 -c auto_exposure=1 -c exposure_time_absolute={constants.settings[LEDMmode]['exposureTime']}",
                    shell=True)
Example #26
0
class LedManager:
    def __init__(self, brightness=None):
        if brightness == None:
            brightness = cs.LED_STRIP_BRIGHTNESS
        if brightness < 0:
            brightness = 0
        elif brightness > 255:
            brightness = 255
        self.strip = Adafruit_NeoPixel(cs.LED_COUNT, cs.LED_PIN,
                                       cs.LED_FREQ_HZ, cs.LED_DMA,
                                       cs.LED_INVERT, brightness,
                                       cs.LED_CHANNEL)
        self.strip.begin()
        self.OFF_COLOR = Color(0, 0, 0)
        self.R = Color(255, 0, 0)
        self.G = Color(0, 255, 0)
        self.B = Color(0, 0, 255)
        self.W = Color(255, 255, 255)
        self.DEFAULT_COLOR = Color(cs.LED_STRIP_DEFAULT_COLOR[0],
                                   cs.LED_STRIP_DEFAULT_COLOR[1],
                                   cs.LED_STRIP_DEFAULT_COLOR[2])

    def getColorFromTuple(self, rgb):
        return Color(rgb[0], rgb[1], rgb[2])

    def test(self):
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(i, self.R)
        self.strip.show()
        time.sleep(1)
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(i, self.G)
        self.strip.show()
        time.sleep(1)
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(i, self.B)
        self.strip.show()
        time.sleep(1)
        self.clear()

    def testWheel(self, pos):
        # from https://github.com/jgarff/rpi_ws281x/blob/master/python/examples/strandtest.py
        """Generate rainbow colors across 0-255 positions."""
        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 testTheaterChaseRainbow(self, wait_ms=50):
        # from https://github.com/jgarff/rpi_ws281x/blob/master/python/examples/strandtest.py
        """Rainbow movie theater light style chaser animation."""
        for j in range(256):
            for q in range(3):
                for i in range(0, self.strip.numPixels(), 3):
                    self.strip.setPixelColor(i + q,
                                             self.testWheel((i + j) % 255))
                self.strip.show()
                time.sleep(wait_ms / 1000.0)
                for i in range(0, self.strip.numPixels(), 3):
                    self.strip.setPixelColor(i + q, 0)

    def testRightLeftBack(self):
        for i in cs.LEDS_RIGHT:
            self.strip.setPixelColor(i, self.R)
        self.strip.show()
        time.sleep(1)
        for i in cs.LEDS_BACK:
            self.strip.setPixelColor(i, self.G)
        self.strip.show()
        time.sleep(1)
        for i in cs.LEDS_LEFT:
            self.strip.setPixelColor(i, self.B)
        self.strip.show()
        time.sleep(1)
        for i in cs.LEDS_BEFORE:
            self.strip.setPixelColor(i, self.W)
        self.strip.show()
        time.sleep(1)
        for i in cs.LEDS_AFTER:
            self.strip.setPixelColor(i, self.W)
        self.strip.show()
        time.sleep(1)

    def clear(self):
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(i, self.OFF_COLOR)
        self.strip.show()

    def loadUserMode(self):
        col = self.getColorFromTuple(cs.USER_LOAD_COLOR)
        self.clear()
        time.sleep(0.3)
        for i in range(self.strip.numPixels(), 0, -1):
            self.strip.setPixelColor(i, col)
            time.sleep(0.1)
            self.strip.show()
        self.blink(blinkTime=0.6, col=col)

    def unloadUserMode(self):
        col = self.getColorFromTuple(cs.USER_LOAD_COLOR)
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(i, self.OFF_COLOR)
            time.sleep(0.1)
            self.strip.show()

    def showResult(self, result):
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(
                i, self.R if
                (i < result * self.strip.numPixels() / 6.) else self.OFF_COLOR)
        self.strip.show()

    def setLeds(self, leds, r, g, b):
        for i in leds:
            self.strip.setPixelColor(i, Color(r, g, b))
        self.strip.show()

    def setAllLeds(self, color=None, r=None, g=None, b=None):
        if color is None:
            color = self.DEFAULT_COLOR
        if r is not None and g is not None and b is not None:
            color = Color(clamp255(r), clamp255(g), clamp255(b))
        for i in range(self.strip.numPixels()):
            self.strip.setPixelColor(i, color)
        self.strip.show()

    def blink(self, blinkTime=0.01, col=None, repeat=3, keepLight=True):
        if col is None:
            col = self.W
        for i in range(repeat):
            self.setAllLeds(col)
            time.sleep(blinkTime)
            self.clear()
            time.sleep(blinkTime)
        if keepLight:
            self.setAllLeds(col)