from blinkstick import blinkstick from random import randint, choice from time import sleep def random_grb(): """ Get a random GRB array. """ # get a random initial color return [ randint(1, 255), randint(1, 255), randint(1, 255) ] def set_all_leds(device, grb=[0,0,0]): """ Takes a GRB color array as input and sets the color on all LEDs. """ return_value = device.set_led_data(0, grb*32) sleep(0.02) # minimal delay to not crash the blinkstick return return_value def morph_channel(color, steps): """ Takes an int between 0-255 and either increments or decreases it by the specified steps. """ direction = choice([-1, 1]) color_candidate = color+steps*direction # if we go out of bounds reverse the direction if color_candidate < 0: return color+steps*direction*-1 elif color_candidate > 255: return color+steps*direction*-1 else: return color_candidate def morph_grb(grb, steps, mode='single'): """ Morphs a GRB array randomly by the specified steps. Available modes: single - only morph a single color all - morph all colors """ if mode == 'single': color_index = randint(0, len(grb)-1) grb[color_index] = morph_channel(grb[color_index], steps) elif mode == 'all': for color_index in range(len(grb)): grb[color_index] = morph_channel(grb[color_index], steps) else: raise Exception(f'Mode "{mode}" is not supported.') return grb def rainbow(device, min_value=1, max_value=255): """ Takes an int between 0-255 and either increments or decreases it by the specified steps. """ direction = [ choice([-1, 1]), choice([-1, 1]), choice([-1, 1]) ] grb = [ randint(min_value, max_value), randint(min_value, max_value), randint(min_value, max_value) ] channel = randint(0, 2) while True: #channel = (channel + 1) % 3 channel = randint(0, 2) for i in range(30): candidate = grb[channel] + 1 * direction[channel] # if we go out of bounds reverse the direction if candidate < min_value or candidate > max_value: direction[channel] = direction[channel] * -1 else: grb[channel] = candidate set_all_leds(device, grb) device = blinkstick.find_first() rainbow(device)