from time import sleep import neopixel import board import logger import pattern def defaultPattern(n, t, pv): return (t % 255, 255, 255) class LightStrip: def __init__(self, data_pin=board.D18, string_length=300, brightness=0.7, pixel_order=neopixel.GRB, max_changes=5): self.data_pin = data_pin self.np = neopixel.NeoPixel( self.data_pin, string_length, brightness=brightness, auto_write=True, pixel_order=pixel_order) self.pattern = defaultPattern self.cur_tick = 0 self.cur_index = 0 self.max_changes = max_changes self.cur_pattern = [] def get_light_level(self): return self.np.brightness def set_light_level(self, level): self.np.brightness = level def set_pattern(self, pattern_callback): self.pattern = pattern_callback def get_next_pattern_tick(self): np = self.np n = np.n t = self.cur_tick if not len(self.cur_pattern) >= n - 1: li = [(255, 255, 255)] * (n - len(self.cur_pattern)) self.cur_pattern.extend(li) for i in range(n): self.cur_pattern[i] = self.pattern(i, t, np[i]) self.cur_tick = t + 1 def tick(self): np = self.np t = self.cur_tick n = np.n if not len(self.cur_pattern) >= n - 1: self.get_next_pattern_tick() changes = 0 ind = self.cur_index for i in range(ind, n): col = self.cur_pattern[i] self.cur_index = i logger.debug("TEST VALUES: np {} col {} same {}".format( tuple(np[i]), col, tuple(np[i]) != col)) if tuple(np[i]) != col: changes = changes + 1 np[i] = col logger.debug( "CHANGE COLOR OF PIXEL {} TO {} ON TICK {}".format(i, col, t)) if changes >= self.max_changes: break if self.cur_index >= (n-1): self.get_next_pattern_tick() self.cur_index = 0