leds/light_manager.py

68 lines
2 KiB
Python
Raw Normal View History

from time import sleep
import neopixel
import board
2020-11-08 07:31:45 +00:00
import logger
2020-11-08 07:16:30 +00:00
import pattern
2020-11-08 03:28:58 +00:00
2020-11-08 07:16:30 +00:00
def defaultPattern(n, t, pv):
2020-11-08 07:47:10 +00:00
return (t % 255, 255, 255)
2020-11-08 03:28:58 +00:00
class LightStrip:
2020-11-12 09:48:19 +00:00
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
2020-11-08 03:28:58 +00:00
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
2020-11-07 21:07:28 +00:00
self.cur_index = 0
self.max_changes = max_changes
2020-11-07 21:07:28 +00:00
self.cur_pattern = []
2020-11-08 03:28:58 +00:00
def get_light_level(self):
return self.np.brightness
def set_light_level(self, level):
self.np.brightness = level
2020-11-08 07:16:30 +00:00
def set_pattern(self, pattern_callback):
2020-11-08 03:28:58 +00:00
self.pattern = pattern_callback
def get_next_pattern_tick(self):
2020-11-08 07:16:30 +00:00
np = self.np
n = np.n
2020-11-08 03:28:58 +00:00
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):
2020-11-08 07:16:30 +00:00
self.cur_pattern[i] = self.pattern(i, t, np[i])
2020-11-08 03:28:58 +00:00
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
2020-11-08 07:37:40 +00:00
logger.debug("TEST VALUES: np {} col {} same {}".format(
2020-11-08 07:43:11 +00:00
tuple(np[i]), col, tuple(np[i]) != col))
2020-11-08 03:28:58 +00:00
if tuple(np[i]) != col:
changes = changes + 1
np[i] = col
2020-11-08 07:37:40 +00:00
logger.debug(
2020-11-08 03:28:58 +00:00
"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