diff --git a/src/main.py b/src/main.py index 4134d06..db405b0 100644 --- a/src/main.py +++ b/src/main.py @@ -8,7 +8,8 @@ import utime import machine import time import wifi - +import json +from p2p import p2p async def main(): settings = Settings() @@ -26,47 +27,24 @@ async def main(): patterns.tick() await asyncio.sleep_ms(1) - async def espnow(): - e = aioespnow.AIOESPNow() # Returns AIOESPNow enhanced with async support - e.active(True) - async for mac, msg in e: - print(msg) - settings.set_settings(msg, patterns) - print("should not print") - - async def wifi_connect(): - for i in range(10): - config = wifi.connect(settings.get("wifi_ssid", ""), - settings.get("wifi_password", ""), - settings.get("wifi_ip", ""), - settings.get("wifi_gateway", "") - ) - if config: - print(config) - break - await asyncio.sleep_ms(500) - w = web(settings, patterns) print(settings) # start the server in a bacakground task print("Starting") server = asyncio.create_task(w.start_server(host="0.0.0.0", port=80)) - #wdt = machine.WDT(timeout=10000) - #wdt.feed() + wdt = machine.WDT(timeout=10000) + wdt.feed() - - asyncio.create_task(wifi_connect()) asyncio.create_task(tick()) - asyncio.create_task(espnow()) + asyncio.create_task(p2p(settings, patterns)) while True: #print(time.localtime()) - - # gc.collect() - for i in range(60): - #wdt.feed() - await asyncio.sleep_ms(500) + gc.collect() + for i in range(20): + wdt.feed() + await asyncio.sleep_ms(1000) # cleanup before ending the application await server diff --git a/src/p2p.py b/src/p2p.py new file mode 100644 index 0000000..d73636c --- /dev/null +++ b/src/p2p.py @@ -0,0 +1,20 @@ +import asyncio +import aioespnow +import json + +async def p2p(settings, patterns): + e = aioespnow.AIOESPNow() # Returns AIOESPNow enhanced with async support + e.active(True) + async for mac, msg in e: + try: + data = json.loads(msg) + except: + print(f"Failed to load espnow data {msg}") + continue + print(data) + if "names" not in data or settings.get("name") in data.get("names", []): + if "step" in settings and isinstance(settings["step"], int): + patterns.set_pattern_step(settings["step"]) + else: + settings.set_settings(data.get("settings", {}), patterns, data.get("save", False)) + print("should not print") diff --git a/src/patterns.py b/src/patterns.py index ccfc7e9..f2385f8 100644 --- a/src/patterns.py +++ b/src/patterns.py @@ -4,11 +4,10 @@ import utime import random class Patterns: - def __init__(self, pin1, num_leds, color1=(0,0,0), color2=(0,0,0), brightness=127, selected="rainbow_cycle", delay=100): + def __init__(self, pin, num_leds, color1=(0,0,0), color2=(0,0,0), brightness=127, selected="rainbow_cycle", delay=100): # Initialize both NeoPixel strips self.n = NeoPixel(Pin(9, Pin.OUT), num_leds) - self.n2 = NeoPixel(Pin(10, Pin.OUT), num_leds) - + self.n2 = NeoPixel(Pin(10, Pin.OUT), num_leds) # Added self.n2 self.num_leds = num_leds self.pattern_step = 0 self.last_update = utime.ticks_ms() @@ -19,106 +18,194 @@ class Patterns: "on" : self.on, "color_wipe": self.color_wipe_step, "rainbow_cycle": self.rainbow_cycle_step, + "theater_chase": self.theater_chase_step, "blink": self.blink_step, + "random_color_wipe": self.random_color_wipe_step, + "random_rainbow_cycle": self.random_rainbow_cycle_step, + "random_theater_chase": self.random_theater_chase_step, "random_blink": self.random_blink_step, "color_transition": self.color_transition_step, + "external": None } self.selected = selected - self.color1 = color1 - self.color2 = color2 - self.transition_duration = delay * 10 # Default transition duration is 10 times the delay + self.colors = [color1, color2] if color1 != color2 else [color1, (255, 255, 255)] + if not self.colors: + self.colors = [(0, 0, 0)] + + self.transition_duration = delay * 50 + self.hold_duration = delay * 10 self.transition_step = 0 - self.current_color = self.color1 + self.current_color_idx = 0 + self.current_color = self.colors[self.current_color_idx] + + self.hold_start_time = utime.ticks_ms() + def sync(self): self.pattern_step=0 - self.last_update = utime.ticks_ms() + self.last_update = utime.ticks_ms() - self.delay + if self.selected == "color_transition": + self.transition_step = 0 + self.current_color_idx = 0 + self.current_color = self.colors[self.current_color_idx] + self.hold_start_time = utime.ticks_ms() + self.tick() + + def set_pattern_step(self, step): + self.pattern_step = step def tick(self): if self.patterns[self.selected]: self.patterns[self.selected]() - def update_num_leds(self, pin1, pin2, num_leds): - # Re-initialize both NeoPixel strips with the new number of LEDs - self.n = NeoPixel(Pin(pin1, Pin.OUT), num_leds) - self.n2 = NeoPixel(Pin(pin2, Pin.OUT), num_leds) + def update_num_leds(self, pin, num_leds): + # Re-initialize both strips if num_leds changes + self.n = NeoPixel(Pin(9, Pin.OUT), num_leds) + self.n2 = NeoPixel(Pin(10, Pin.OUT), num_leds) # Update self.n2 as well self.num_leds = num_leds self.pattern_step = 0 def set_delay(self, delay): self.delay = delay - # Update transition duration when delay changes for color_transition pattern - if self.selected == "color_transition": - self.transition_duration = self.delay * 10 # Or some other multiplier + self.transition_duration = self.delay * 50 + self.hold_duration = self.delay * 10 def set_brightness(self, brightness): self.brightness = brightness def set_color1(self, color): - self.color1 = color - if self.selected == "color_transition": - self.transition_step = 0 - self.current_color = self.color1 + if len(self.colors) > 0: + self.colors[0] = color + if self.selected == "color_transition": + if self.current_color_idx == 0: + self.transition_step = 0 + self.current_color = self.colors[0] + self.hold_start_time = utime.ticks_ms() + else: + self.colors.append(color) def set_color2(self, color): - self.color2 = color - if self.selected == "color_transition": - self.transition_step = 0 - self.current_color = self.color1 + if len(self.colors) > 1: + self.colors[1] = color + elif len(self.colors) == 1: + self.colors.append(color) + else: + self.colors.append((0,0,0)) + self.colors.append(color) + def set_colors(self, colors): + if colors and len(colors) >= 2: + self.colors = colors + if self.selected == "color_transition": + self.sync() + elif colors and len(colors) == 1: + self.colors = [colors[0], (255,255,255)] + if self.selected == "color_transition": + print("Warning: 'color_transition' requires at least two colors. Adding a default second color.") + self.sync() + else: + print("Error: set_colors requires a list of at least one color.") + self.colors = [(0,0,0), (255,255,255)] + if self.selected == "color_transition": + self.sync() + + def set_color(self, num, color): + if 0 <= num < len(self.colors): + self.colors[num] = color + if self.selected == "color_transition": + current_from_idx = self.current_color_idx + current_to_idx = (self.current_color_idx + 1) % len(self.colors) + if num == current_from_idx or num == current_to_idx: + self.transition_step = 0 + self.current_color_idx = current_from_idx + self.current_color = self.colors[self.current_color_idx] + self.hold_start_time = utime.ticks_ms() + return True + elif num == len(self.colors): + self.colors.append(color) + return True + return False + + def add_color(self, color): + self.colors.append(color) + if self.selected == "color_transition" and len(self.colors) == 2: + self.sync() + + + def del_color(self, num): + if 0 <= num < len(self.colors): + del self.colors[num] + if self.selected == "color_transition": + if len(self.colors) < 2: + print("Warning: Not enough colors for 'color_transition'. Switching to 'on'.") + self.select("on") + else: + self.current_color_idx %= len(self.colors) + self.transition_step = 0 + self.current_color = self.colors[self.current_color_idx] + self.hold_start_time = utime.ticks_ms() + return True + return False + def apply_brightness(self, color): return tuple(int(c * self.brightness / 255) for c in color) def select(self, pattern): if pattern in self.patterns: self.selected = pattern - self.sync() # Reset pattern state when selecting a new pattern + self.sync() if pattern == "color_transition": - self.transition_step = 0 - self.current_color = self.color1 - self.transition_duration = self.delay * 10 # Initialize transition duration + if len(self.colors) < 2: + print("Warning: 'color_transition' requires at least two colors. Switching to 'on'.") + self.selected = "on" + self.sync() + else: + self.transition_step = 0 + self.current_color_idx = 0 + self.current_color = self.colors[self.current_color_idx] + self.hold_start_time = utime.ticks_ms() + self.transition_duration = self.delay * 50 + self.hold_duration = self.delay * 10 return True return False def set(self, i, color): - # Set the color for the specified LED on both strips self.n[i] = color - self.n2[i] = color + self.n2[i] = color # Set color on the second strip def write(self): - # Write the color data to both strips self.n.write() - self.n2.write() + self.n2.write() # Write to the second strip def fill(self, color=None): - fill_color = color if color is not None else self.color1 - # Fill both strips with the specified color + fill_color = color if color is not None else self.colors[0] for i in range(self.num_leds): self.n[i] = fill_color - self.n2[i] = fill_color - self.write() # Call write after filling both + self.n2[i] = fill_color # Fill the second strip + self.n.write() + self.n2.write() # Write after filling both def off(self): self.fill((0, 0, 0)) def on(self): - self.fill(self.apply_brightness(self.color1)) - + self.fill(self.apply_brightness(self.colors[0])) def color_wipe_step(self): - color = self.apply_brightness(self.color1) + color = self.apply_brightness(self.colors[0]) current_time = utime.ticks_ms() if utime.ticks_diff(current_time, self.last_update) >= self.delay: if self.pattern_step < self.num_leds: for i in range(self.num_leds): self.n[i] = (0, 0, 0) - self.n2[i] = (0, 0, 0) # Clear the second strip as well + self.n2[i] = (0, 0, 0) # Clear both strips self.n[self.pattern_step] = self.apply_brightness(color) - self.n2[self.pattern_step] = self.apply_brightness(color) # Set the LED on the second strip - self.write() # Write to both strips + self.n2[self.pattern_step] = self.apply_brightness(color) # Set on second strip + self.n.write() + self.n2.write() # Write both self.pattern_step += 1 else: self.pattern_step = 0 @@ -139,10 +226,10 @@ class Patterns: for i in range(self.num_leds): rc_index = (i * 256 // self.num_leds) + self.pattern_step - color = self.apply_brightness(wheel(rc_index & 255)) - self.n[i] = color - self.n2[i] = color # Set the color on the second strip - self.write() # Write to both strips + self.n[i] = self.apply_brightness(wheel(rc_index & 255)) + self.n2[i] = self.apply_brightness(wheel(rc_index & 255)) # Set on second strip + self.n.write() + self.n2.write() # Write both self.pattern_step = (self.pattern_step + 1) % 256 self.last_update = current_time @@ -151,12 +238,13 @@ class Patterns: if utime.ticks_diff(current_time, self.last_update) >= self.delay: for i in range(self.num_leds): if (i + self.pattern_step) % 3 == 0: - color = self.apply_brightness(self.color1) + self.n[i] = self.apply_brightness(self.colors[0]) + self.n2[i] = self.apply_brightness(self.colors[0]) # Set on second strip else: - color = (0, 0, 0) - self.n[i] = color - self.n2[i] = color # Set the color on the second strip - self.write() # Write to both strips + self.n[i] = (0, 0, 0) + self.n2[i] = (0, 0, 0) # Clear on second strip + self.n.write() + self.n2.write() # Write both self.pattern_step = (self.pattern_step + 1) % 3 self.last_update = current_time @@ -164,7 +252,7 @@ class Patterns: current_time = utime.ticks_ms() if utime.ticks_diff(current_time, self.last_update) >= self.delay: if self.pattern_step % 2 == 0: - self.fill(self.apply_brightness(self.color1)) + self.fill(self.apply_brightness(self.colors[0])) else: self.fill((0, 0, 0)) self.pattern_step = (self.pattern_step + 1) % 2 @@ -177,10 +265,11 @@ class Patterns: if self.pattern_step < self.num_leds: for i in range(self.num_leds): self.n[i] = (0, 0, 0) - self.n2[i] = (0, 0, 0) # Clear the second strip as well + self.n2[i] = (0, 0, 0) # Clear both strips self.n[self.pattern_step] = self.apply_brightness(color) - self.n2[self.pattern_step] = self.apply_brightness(color) # Set the LED on the second strip - self.write() # Write to both strips + self.n2[self.pattern_step] = self.apply_brightness(color) # Set on second strip + self.n.write() + self.n2.write() # Write both self.pattern_step += 1 else: self.pattern_step = 0 @@ -202,10 +291,10 @@ class Patterns: random_offset = random.randint(0, 255) for i in range(self.num_leds): rc_index = (i * 256 // self.num_leds) + self.pattern_step + random_offset - color = self.apply_brightness(wheel(rc_index & 255)) - self.n[i] = color - self.n2[i] = color # Set the color on the second strip - self.write() # Write to both strips + self.n[i] = self.apply_brightness(wheel(rc_index & 255)) + self.n2[i] = self.apply_brightness(wheel(rc_index & 255)) # Set on second strip + self.n.write() + self.n2.write() # Write both self.pattern_step = (self.pattern_step + 1) % 256 self.last_update = current_time @@ -215,12 +304,13 @@ class Patterns: color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) for i in range(self.num_leds): if (i + self.pattern_step) % 3 == 0: - pixel_color = self.apply_brightness(color) + self.n[i] = self.apply_brightness(color) + self.n2[i] = self.apply_brightness(color) # Set on second strip else: - pixel_color = (0, 0, 0) - self.n[i] = pixel_color - self.n2[i] = pixel_color # Set the color on the second strip - self.write() # Write to both strips + self.n[i] = (0, 0, 0) + self.n2[i] = (0, 0, 0) # Clear on second strip + self.n.write() + self.n2.write() # Write both self.pattern_step = (self.pattern_step + 1) % 3 self.last_update = current_time @@ -235,46 +325,42 @@ class Patterns: self.pattern_step = (self.pattern_step + 1) % 2 self.last_update = current_time - def interpolate_color(self, color_a, color_b, factor): - """Interpolates between two colors.""" - return tuple(int(a + (b - a) * factor) for a, b in zip(color_a, color_b)) - def color_transition_step(self): current_time = utime.ticks_ms() - # Use delay for how often to update the transition, not for the duration - if utime.ticks_diff(current_time, self.last_update) >= 1: # Update frequently for smooth transition - self.transition_step += utime.ticks_diff(current_time, self.last_update) + + if utime.ticks_diff(current_time, self.hold_start_time) < self.hold_duration: + self.fill(self.apply_brightness(self.current_color)) self.last_update = current_time + return + + if utime.ticks_diff(current_time, self.last_update) >= self.delay: + num_colors = len(self.colors) + if num_colors < 2: + self.select("on") + return + + from_color = self.colors[self.current_color_idx] + to_color_idx = (self.current_color_idx + 1) % num_colors + to_color = self.colors[to_color_idx] + + if self.transition_duration > 0: + interp_factor = self.transition_step / self.transition_duration + else: + interp_factor = 1.0 + + r = int(from_color[0] + (to_color[0] - from_color[0]) * interp_factor) + g = int(from_color[1] + (to_color[1] - from_color[1]) * interp_factor) + b = int(from_color[2] + (to_color[2] - from_color[2]) * interp_factor) + + self.current_color = (r, g, b) + self.fill(self.apply_brightness(self.current_color)) + + self.transition_step += self.delay if self.transition_step >= self.transition_duration: - # Transition complete, swap colors and restart - self.color1, self.color2 = self.color2, self.color1 + self.current_color_idx = to_color_idx + self.current_color = self.colors[self.current_color_idx] self.transition_step = 0 + self.hold_start_time = current_time - # Calculate the interpolation factor (0 to 1) - factor = self.transition_step / self.transition_duration - - # Get the interpolated color and apply brightness - interpolated_color = self.interpolate_color(self.color1, self.color2, factor) - self.current_color = self.apply_brightness(interpolated_color) - - # Fill the LEDs on both strips with the current interpolated color - self.fill(self.current_color) - - -if __name__ == "__main__": - # Use different pins for the two strips - p = Patterns(9, 10, 180) - p.set_color1((255,0,0)) - p.set_color2((0,255,0)) - #p.set_delay(10) - try: - while True: - for key in p.patterns: - print(key) - p.select(key) - for _ in range(2000): - p.tick() - utime.sleep_ms(1) - except KeyboardInterrupt: - p.fill((0, 0, 0)) + self.last_update = current_time diff --git a/src/settings.py b/src/settings.py index 60e5afe..fa7fa71 100644 --- a/src/settings.py +++ b/src/settings.py @@ -23,10 +23,7 @@ class Settings(dict): self["color_order"] = "rgb" self["name"] = f"led-{ubinascii.hexlify(wifi.get_mac()).decode()}" self["ap_password"] = "" - self["wifi_ssid"] = "" - self["wifi_password"] = "" - self["wifi_ip"] = "" - self["wifi_gateway"] = "" + self["id"] = 0 def save(self): try: @@ -48,19 +45,22 @@ class Settings(dict): self.set_defaults() self.save() - def set_settings(self, raw_json, patterns): - patterns.sync() + def set_settings(self, data, patterns, save): try: - data = json.loads(raw_json) print(data) for key, value in data.items(): print(key, value) - if key == "color1": + if key == "colors": + buff = [] + for color in value: + buff.append(tuple(int(color[i:i+2], 16) for i in self.color_order)) + patterns.set_colors(buff) + elif key == "color1": patterns.set_color1(tuple(int(value[i:i+2], 16) for i in self.color_order)) # Convert hex to RGB elif key == "color2": patterns.set_color2(tuple(int(value[i:i+2], 16) for i in self.color_order)) # Convert hex to RGB elif key == "num_leds": - patterns.update_num_leds(4, value) + patterns.update_num_leds(self["led_pin"], value) elif key == "pattern": if not patterns.select(value): return "Pattern doesn't exist", 400 @@ -77,11 +77,20 @@ class Settings(dict): elif key == "color_order": if value == "rbg": self.color_order = (1, 5, 3) else: self.color_order = (1, 3, 5) + pass + elif key == "id": + pass + elif key == "led_pin": + patterns.update_num_leds(value, self["num_leds"]) else: return "Invalid key", 400 self[key] = value + #print(self) + patterns.sync() + if save: self.save() - return "OK", 200 + print("Saved settings") + return "OK", 200 except (KeyError, ValueError): return "Bad request", 400 diff --git a/src/static/main.css b/src/static/main.css index d321d13..15226a5 100644 --- a/src/static/main.css +++ b/src/static/main.css @@ -98,3 +98,12 @@ input[type="range"]::-moz-range-thumb { #connection-status.closed { background-color: red; } + +#color_order_form label, +#color_order_form input[type="radio"] { + /* Ensures they behave as inline elements */ + display: inline-block; + /* Adds some space between them for readability */ + margin-right: 10px; + vertical-align: middle; /* Aligns them nicely if heights vary */ +} diff --git a/src/static/main.js b/src/static/main.js index da7c0a9..9e00994 100644 --- a/src/static/main.js +++ b/src/static/main.js @@ -150,6 +150,30 @@ async function updateName(event) { sendWebSocketData({ name: name }); } +async function updateID(event) { + event.preventDefault(); + const id = document.getElementById("id").value; + sendWebSocketData({ id: parseInt(id) }); +} + +async function updateLedPin(event) { + event.preventDefault(); + const ledpin = document.getElementById("led_pin").value; + sendWebSocketData({ led_pin: parseInt(ledpin) }); +} + +function handleRadioChange(event) { + event.preventDefault(); + console.log("Selected color order:", event.target.value); + // Add your specific logic here + if (event.target.value === "rgb") { + console.log("RGB order selected!"); + } else if (event.target.value === "rbg") { + console.log("RBG order selected!"); + } + sendWebSocketData({ color_order: event.target.value }); +} + function createPatternButtons(patterns) { const container = document.getElementById("pattern_buttons"); container.innerHTML = ""; // Clear previous buttons @@ -184,11 +208,17 @@ document.addEventListener("DOMContentLoaded", async function () { .getElementById("num_leds_form") .addEventListener("submit", updateNumLeds); document.getElementById("name_form").addEventListener("submit", updateName); + document.getElementById("id_form").addEventListener("submit", updateID); + document + .getElementById("led_pin_form") + .addEventListener("submit", updateLedPin); document.getElementById("delay").addEventListener("touchend", updateDelay); document .getElementById("brightness") .addEventListener("touchend", updateBrightness); + document.getElementById("rgb").addEventListener("change", handleRadioChange); + document.getElementById("rbg").addEventListener("change", handleRadioChange); document.querySelectorAll(".pattern_button").forEach((button) => { console.log(button.value); button.addEventListener("click", async (event) => { diff --git a/src/templates/index.html b/src/templates/index.html index 31c67dc..4e1a112 100644 --- a/src/templates/index.html +++ b/src/templates/index.html @@ -79,6 +79,16 @@ /> +
+ + + +
@@ -90,6 +100,23 @@ />
+
+ + + +
+
+ + + + +
+

Mac address: {{mac}}

diff --git a/src/web.py b/src/web.py index aba0213..a66c4f0 100644 --- a/src/web.py +++ b/src/web.py @@ -33,8 +33,9 @@ def web(settings, patterns): while True: data = await ws.receive() if data: + # Process the received data - _, status_code = settings.set_settings(data, patterns) + _, status_code = settings.set_settings(json.loads(data), patterns, True) #await ws.send(status_code) else: break