def on_connect(client, userdata, flags, rc): global strip_odd global strip_even strip_odd = Adafruit_NeoPixel(LED_COUNT, 12, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, 0) strip_even = Adafruit_NeoPixel(LED_COUNT, 13, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, 1) strip_3 = Adafruit_NeoPixel(LED_COUNT, 18, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, 0) strip_4 = Adafruit_NeoPixel(LED_COUNT, 19, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, 1) strip_odd.begin() strip_even.begin() strip_3.begin() strip_4.begin() #Blackout blackout(strip_odd) blackout(strip_even) blackout(strip_3) blackout(strip_4) client.subscribe("shelf/#") publish.single("shelf/report/status", 'false', hostname="localhost") publish.single("shelf/report/brightness", '0', hostname="localhost") publish.single("shelf/report/hue", '0', hostname="localhost") publish.single("shelf/report/saturation", '0', hostname="localhost")
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()
def add_stripe( self, NUMPIXELS, # Amount of pixels (LEDs) the strip contains PIN, # GPIO pin the strip is connected to (must be PWM pin, RPi4: 12, 13, 18, 19) FREQUENCY_HZ=800000, # PWM Frequency the strip operates in DMA_CHANNEL=10, # DMA Channel (1 to 14) PWM_CHANNEL=0, # PWM Channel (0 or 1) BRIGHTNESS=128, # For strips that support brightness control (0 to 255) INVERT=False, # If using a level shifter that causes signal inversion, set this to true STRIP_TYPE='WS2811_STRIP_GRB', # Available types [WS2811_STRIP_GRB, ] ): strip = Adafruit_NeoPixel(NUMPIXELS, PIN, FREQUENCY_HZ, DMA_CHANNEL, INVERT, BRIGHTNESS, PWM_CHANNEL, self.strip_types[STRIP_TYPE]) strip.begin() self.strips.append(strip)
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)
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)
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)
def _init_ws2812(self): from rpi_ws281x import Adafruit_NeoPixel, WS2812_STRIP LED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz) LED_DMA = 10 # DMA channel to use for generating signal (try 5) LED_BRIGHTNESS = 255 # 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 = 0 LED_STRIP = WS2812_STRIP ws2812 = Adafruit_NeoPixel( self.size, self.pin, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL, LED_STRIP, ) ws2812.begin() return ws2812
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()
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()
strip.show() # Main program logic follows: if __name__ == '__main__': # Create NeoPixel objects with appropriate configuration for each strip. strip1 = Adafruit_NeoPixel(LED_1_COUNT, LED_1_PIN, LED_1_FREQ_HZ, LED_1_DMA, LED_1_INVERT, LED_1_BRIGHTNESS, LED_1_CHANNEL, LED_1_STRIP) strip2 = Adafruit_NeoPixel(LED_2_COUNT, LED_2_PIN, LED_2_FREQ_HZ, LED_2_DMA, LED_2_INVERT, LED_2_BRIGHTNESS, LED_2_CHANNEL, LED_2_STRIP) # Intialize the library (must be called once before other functions). strip1.begin() strip2.begin() print('Press Ctrl-C to quit.') # Black out any LEDs that may be still on for the last run blackout(strip1) blackout(strip2) while True: # Multi Color wipe animations. multiColorWipe(Color(255, 0, 0), Color(255, 0, 0)) # Red wipe multiColorWipe(Color(0, 255, 0), Color(0, 255, 0)) # Blue wipe multiColorWipe(Color(0, 0, 255), Color(0, 0, 255)) # Green wipe multiColorWipe(Color(255, 255, 255), Color(255, 255, 255)) # Composite White wipe
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()
def run(): global rainbow_table for i in range(360): rainbow_table.append(color_hsv(i, 100, 40)) context = zmq.Context() receiver = context.socket(zmq.PULL) receiver.bind("tcp://127.0.0.1:5593") strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL) strip.begin() ws_state = get_state() ws_scenes = get_scenes() ws_modes = get_modes() wait_ms = 100 timer_effect = 0 timer_state = 0 offset = 0 mod = 0 value = 0 while (True): # Update scene if timer_state >= 200: try: m = receiver.recv_string(zmq.NOBLOCK) except zmq.ZMQError as e: if e.errno == zmq.EAGAIN: pass else: if m == "UPDATE": ws_state = get_state() ws_scenes = get_scenes() offset = 0 mod = 0 value = 0 timer_effect = wait_ms timer_state = 0 # Generate effect if timer_effect >= wait_ms: if ws_state['enable'] == 1: for i in ws_scenes['scenes']: if i['id'] is ws_state['scene']: m = i['mode_id'] wait_ms = i['wait_ms'] if i['def'] is True: colors = i['colors'] # Mode 0 (static) if m is 0: if i['def'] is True: cycle(strip, colors) else: rainbow(strip) # Mode 1 (cyclic) elif m is 1: if i['def'] is True: offset = (offset + 1) % LED_COUNT cycle(strip, colors, offset) else: offset = (offset + 1) % LED_COUNT rainbow(strip, offset) # Mode 2 (fading) elif m is 2: if i['def'] is True: num = len(colors) if mod is 0: value += 1 if value is colors[offset]['v']: mod = 1 elif mod is 1: value -= 1 if value is 0: offset = (offset + 1) % num mod = 0 fading(strip, colors, offset, value) # Clear strip if enable is 0 else: clear(strip) wait_ms = 100 timer_effect = 0 time.sleep(1 / 1000.0) timer_effect += 1 timer_state += 1
GPIO.setmode(GPIO.BCM) LED_COUNT = 2340 # Number of LED pixels. LED_PIN = 18 # GPIO pin connected to the pixels (must support PWM! GPIO 13 or 18 on RPi 3). LED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz) LED_DMA = 11 # DMA channel to use for generating signal (Between 1 and 14) LED_BRIGHTNESS = 128 # 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 # 0 or 1 LED_STRIP = ws.WS2811_STRIP_GRB STRIP = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL, LED_STRIP) STRIP.begin() LINES_LED = [ [0, 77], #0 [312, 234], #1 [313, 389], #2 [546, 623], #3 [545, 468], #4 [78, 155], #5 [156, 233], #6 [390, 467], #7 [624, 701], #8 [702, 779], #9 [1559, 1482], #10 [780, 857], #11
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)
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))
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
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)
from smbus import SMBus import gpiozero import RPi.GPIO as rpi from time import sleep import threading from rpi_ws281x import Adafruit_NeoPixel, Color bus = 0 panel = Adafruit_NeoPixel(64, 18, 800000, 5, False, 50) panel.begin() color = Color(255, 255, 255) def frange(start, stop, step): i = start if (start < stop): while i <= stop: yield i i += step # For some reason, += doesn't always add an exact decimal, so we have to round the value i = round(i, 1) else: while i >= stop: yield i i += step # For some reason, += doesn't always add an exact decimal, so we have to round the value i = round(i, 1)
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
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)
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
from rpi_ws281x import Adafruit_NeoPixel from constants import * from utils import colorWipe from note_listener import NoteListener from note_trainer import NoteTrainer from fade_worker import FadeWorker from loader import Loader from threading import Thread print("Setting up neopixels ..."); neopixel = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL) neopixel.begin() if __name__ == '__main__': loader = Loader(neopixel) loader.start() time.sleep(7) # un si beau loader faut quand meme lui laisser le temps de charger ! try: note_listener = NoteListener(neopixel, 70, 695) # from 70 to 700Hz note_listener_monitor = FadeWorker(note_listener, 50) note_listener_monitor.start() note_trainer = NoteTrainer() note_trainer.addNoteListener(note_listener) note_trainer.main(loader)
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)
import socket #ip # 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', './')
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)