Compare commits
31 Commits
fa0578349b
...
dev
Author | SHA1 | Date | |
---|---|---|---|
7547efe7fd | |||
d2826a0f63 | |||
87fc74bb51 | |||
03f3f02da8 | |||
524db5e979 | |||
279416cded | |||
fbd14f2e16 | |||
1989f6f5c9 | |||
a19b1e86f2 | |||
c63e907204 | |||
b7920e224f | |||
42e92dafc8 | |||
0b6eb9724f | |||
55ef5c1580 | |||
c15f9787a7 | |||
3d0078f118 | |||
9e72dba035 | |||
3d7dd754eb | |||
2dd20fa51b | |||
d33bd6b0e4 | |||
8902adf18c | |||
9abd425f46 | |||
ee28b5805d | |||
ec29dbdd01 | |||
3fa9377438 | |||
ec049b52c0 | |||
a009ea85bc | |||
bd2e6e56cf | |||
37c7280a15 | |||
2f10d4cabd | |||
385dcffe68 |
@@ -5,4 +5,5 @@ from settings import Settings
|
|||||||
s = Settings()
|
s = Settings()
|
||||||
|
|
||||||
name = s.get('name', 'led')
|
name = s.get('name', 'led')
|
||||||
wifi.ap(name, '')
|
password = s.get("ap_password", "")
|
||||||
|
wifi.ap(name, password)
|
||||||
|
49
src/main.py
49
src/main.py
@@ -1,6 +1,6 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
import aioespnow
|
import aioespnow
|
||||||
from settings import Settings, set_settings
|
from settings import Settings
|
||||||
from web import web
|
from web import web
|
||||||
from patterns import Patterns
|
from patterns import Patterns
|
||||||
import gc
|
import gc
|
||||||
@@ -8,52 +8,43 @@ import utime
|
|||||||
import machine
|
import machine
|
||||||
import time
|
import time
|
||||||
import wifi
|
import wifi
|
||||||
|
import json
|
||||||
|
from p2p import p2p
|
||||||
|
|
||||||
async def main():
|
async def main():
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
settings = Settings()
|
settings = Settings()
|
||||||
|
|
||||||
patterns = Patterns(4, settings["num_leds"], selected=settings["pattern"])
|
patterns = Patterns(settings["led_pin"], settings["num_leds"], selected=settings["pattern"])
|
||||||
patterns.set_color1(tuple(int(settings["color1"][i:i+2], 16) for i in (1, 5, 3)))
|
if settings["color_order"] == "rbg": color_order = (1, 5, 3)
|
||||||
patterns.set_color2(tuple(int(settings["color2"][i:i+2], 16) for i in (1, 5, 3)))
|
else: color_order = (1, 3, 5)
|
||||||
|
patterns.set_color1(tuple(int(settings["color1"][i:i+2], 16) for i in color_order))
|
||||||
|
patterns.set_color2(tuple(int(settings["color2"][i:i+2], 16) for i in color_order))
|
||||||
patterns.set_brightness(int(settings["brightness"]))
|
patterns.set_brightness(int(settings["brightness"]))
|
||||||
patterns.set_delay(int(settings["delay"]))
|
patterns.set_delay(int(settings["delay"]))
|
||||||
|
|
||||||
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()
|
|
||||||
|
|
||||||
async def tick():
|
async def tick():
|
||||||
while True:
|
while True:
|
||||||
patterns.tick()
|
patterns.tick()
|
||||||
await asyncio.sleep_ms(1)
|
await asyncio.sleep_ms(1)
|
||||||
|
|
||||||
async def espnow():
|
w = web(settings, patterns)
|
||||||
e = aioespnow.AIOESPNow() # Returns AIOESPNow enhanced with async support
|
print(settings)
|
||||||
e.active(True)
|
# start the server in a bacakground task
|
||||||
async for mac, msg in e:
|
print("Starting")
|
||||||
print(msg)
|
server = asyncio.create_task(w.start_server(host="0.0.0.0", port=80))
|
||||||
set_settings(msg, settings, patterns)
|
wdt = machine.WDT(timeout=10000)
|
||||||
print("should not print")
|
wdt.feed()
|
||||||
|
|
||||||
asyncio.create_task(tick())
|
asyncio.create_task(tick())
|
||||||
asyncio.create_task(espnow())
|
asyncio.create_task(p2p(settings, patterns))
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
|
|
||||||
#print(time.localtime())
|
#print(time.localtime())
|
||||||
|
gc.collect()
|
||||||
# gc.collect()
|
for i in range(20):
|
||||||
for i in range(60):
|
wdt.feed()
|
||||||
#wdt.feed()
|
await asyncio.sleep_ms(1000)
|
||||||
await asyncio.sleep_ms(500)
|
|
||||||
|
|
||||||
# cleanup before ending the application
|
# cleanup before ending the application
|
||||||
await server
|
await server
|
||||||
|
20
src/p2p.py
Normal file
20
src/p2p.py
Normal file
@@ -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")
|
375
src/patterns.py
375
src/patterns.py
@@ -14,31 +14,44 @@ class Patterns:
|
|||||||
self.patterns = {
|
self.patterns = {
|
||||||
"off": self.off,
|
"off": self.off,
|
||||||
"on" : self.on,
|
"on" : self.on,
|
||||||
"color_wipe": self.color_wipe_step,
|
|
||||||
"rainbow_cycle": self.rainbow_cycle_step,
|
"rainbow_cycle": self.rainbow_cycle_step,
|
||||||
"theater_chase": self.theater_chase_step,
|
"theater_chase": self.theater_chase_step,
|
||||||
"blink": self.blink_step,
|
"blink": self.blink_step,
|
||||||
"random_color_wipe": self.random_color_wipe_step,
|
"color_transition": self.color_transition_step, # Added new pattern
|
||||||
"random_rainbow_cycle": self.random_rainbow_cycle_step,
|
"flicker": self.flicker_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.selected = selected
|
||||||
self.color1 = color1
|
# Ensure colors list always starts with at least two for robust transition handling
|
||||||
self.color2 = color2
|
self.colors = [color1, color2] if color1 != color2 else [color1, (255, 255, 255)] # Fallback if initial colors are same
|
||||||
self.transition_duration = 50 # Duration of color transition in milliseconds
|
if not self.colors: # Ensure at least one color exists
|
||||||
self.transition_step = 0
|
self.colors = [(0, 0, 0)]
|
||||||
|
|
||||||
|
self.transition_duration = delay * 50 # Default transition duration
|
||||||
|
self.hold_duration = delay * 10 # Default hold duration at each color
|
||||||
|
self.transition_step = 0 # Current step in the transition
|
||||||
|
self.current_color_idx = 0 # Index of the color currently being held/transitioned from
|
||||||
|
self.current_color = self.colors[self.current_color_idx] # The actual blended color
|
||||||
|
|
||||||
|
self.hold_start_time = utime.ticks_ms() # Time when the current color hold started
|
||||||
|
|
||||||
|
|
||||||
def sync(self):
|
def sync(self):
|
||||||
self.pattern_step=0
|
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() # Reset hold time
|
||||||
|
self.tick()
|
||||||
|
|
||||||
|
def set_pattern_step(self, step):
|
||||||
|
self.pattern_step = step
|
||||||
|
|
||||||
def tick(self):
|
def tick(self):
|
||||||
if self.patterns[self.selected]:
|
if self.patterns[self.selected]:
|
||||||
self.patterns[self.selected]()
|
self.patterns[self.selected]()
|
||||||
|
|
||||||
def update_num_leds(self, pin, num_leds):
|
def update_num_leds(self, pin, num_leds):
|
||||||
self.n = NeoPixel(Pin(pin, Pin.OUT), num_leds)
|
self.n = NeoPixel(Pin(pin, Pin.OUT), num_leds)
|
||||||
self.num_leds = num_leds
|
self.num_leds = num_leds
|
||||||
@@ -46,52 +59,145 @@ class Patterns:
|
|||||||
|
|
||||||
def set_delay(self, delay):
|
def set_delay(self, delay):
|
||||||
self.delay = delay
|
self.delay = delay
|
||||||
|
# Update transition duration and hold duration when delay changes
|
||||||
|
self.transition_duration = self.delay * 50
|
||||||
|
self.hold_duration = self.delay * 10
|
||||||
|
|
||||||
|
|
||||||
def set_brightness(self, brightness):
|
def set_brightness(self, brightness):
|
||||||
self.brightness = brightness
|
self.brightness = brightness
|
||||||
|
|
||||||
def set_color1(self, color):
|
def set_color1(self, color):
|
||||||
print(color)
|
if len(self.colors) > 0:
|
||||||
self.color1 = self.apply_brightness(color)
|
self.colors[0] = color
|
||||||
|
if self.selected == "color_transition":
|
||||||
|
# If the first color is changed, potentially reset transition
|
||||||
|
# to start from this new color if we were about to transition from it
|
||||||
|
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):
|
def set_color2(self, color):
|
||||||
self.color2 = self.apply_brightness(color)
|
if len(self.colors) > 1:
|
||||||
|
self.colors[1] = color
|
||||||
def apply_brightness(self, color):
|
elif len(self.colors) == 1:
|
||||||
return tuple(int(c * self.brightness / 255) for c in color)
|
self.colors.append(color)
|
||||||
|
else: # List is empty
|
||||||
|
self.colors.append((0,0,0)) # Dummy color
|
||||||
|
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() # Reset transition if new color list is provided
|
||||||
|
elif colors and len(colors) == 1:
|
||||||
|
self.colors = [colors[0], (255,255,255)] # Add a default second color
|
||||||
|
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)] # Fallback
|
||||||
|
if self.selected == "color_transition":
|
||||||
|
self.sync()
|
||||||
|
|
||||||
|
def set_color(self, num, color):
|
||||||
|
# Changed: More robust index check
|
||||||
|
if 0 <= num < len(self.colors):
|
||||||
|
self.colors[num] = color
|
||||||
|
# If the changed color is part of the current or next transition,
|
||||||
|
# restart the transition for smoother updates
|
||||||
|
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:
|
||||||
|
# If we change a color involved in the current transition,
|
||||||
|
# it's best to restart the transition state for smoothness.
|
||||||
|
self.transition_step = 0
|
||||||
|
self.current_color_idx = current_from_idx # Stay at the current starting color
|
||||||
|
self.current_color = self.colors[self.current_color_idx]
|
||||||
|
self.hold_start_time = utime.ticks_ms() # Reset hold
|
||||||
|
return True
|
||||||
|
elif num == len(self.colors): # Allow setting a new color at the end
|
||||||
|
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:
|
||||||
|
# If we just added the second color needed for transition
|
||||||
|
self.sync()
|
||||||
|
|
||||||
|
|
||||||
|
def del_color(self, num):
|
||||||
|
# Changed: More robust index check and using del for lists
|
||||||
|
if 0 <= num < len(self.colors):
|
||||||
|
del self.colors[num]
|
||||||
|
# If the color being deleted was part of the current transition,
|
||||||
|
# re-evaluate the current_color_idx
|
||||||
|
if self.selected == "color_transition":
|
||||||
|
if len(self.colors) < 2: # Need at least two colors for transition
|
||||||
|
print("Warning: Not enough colors for 'color_transition'. Switching to 'on'.")
|
||||||
|
self.select("on") # Or some other default
|
||||||
|
else:
|
||||||
|
# Adjust index if it's out of bounds after deletion or was the one transitioning from
|
||||||
|
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, brightness_override=None):
|
||||||
|
effective_brightness = brightness_override if brightness_override is not None else self.brightness
|
||||||
|
return tuple(int(c * effective_brightness / 255) for c in color)
|
||||||
|
|
||||||
def select(self, pattern):
|
def select(self, pattern):
|
||||||
if pattern in self.patterns:
|
if pattern in self.patterns:
|
||||||
self.selected = pattern
|
self.selected = pattern
|
||||||
|
self.sync() # Reset pattern state when selecting a new pattern
|
||||||
|
if pattern == "color_transition":
|
||||||
|
if len(self.colors) < 2:
|
||||||
|
print("Warning: 'color_transition' requires at least two colors. Switching to 'on'.")
|
||||||
|
self.selected = "on" # Fallback if not enough colors
|
||||||
|
self.sync() # Re-sync for the new pattern
|
||||||
|
else:
|
||||||
|
self.transition_step = 0
|
||||||
|
self.current_color_idx = 0 # Start from the first color in the list
|
||||||
|
self.current_color = self.colors[self.current_color_idx]
|
||||||
|
self.hold_start_time = utime.ticks_ms() # Reset hold timer
|
||||||
|
self.transition_duration = self.delay * 50 # Initialize transition duration
|
||||||
|
self.hold_duration = self.delay * 10 # Initialize hold duration
|
||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def set(self, i, color):
|
def set(self, i, color):
|
||||||
self.n[i] = color
|
self.n[i] = color
|
||||||
|
|
||||||
def write(self):
|
def write(self):
|
||||||
self.n.write()
|
self.n.write()
|
||||||
|
|
||||||
def fill(self):
|
def fill(self, color=None):
|
||||||
|
fill_color = color if color is not None else self.colors[0]
|
||||||
for i in range(self.num_leds):
|
for i in range(self.num_leds):
|
||||||
self.n[i] = self.color1
|
self.n[i] = fill_color
|
||||||
self.n.write()
|
self.n.write()
|
||||||
|
|
||||||
def off(self):
|
def off(self):
|
||||||
color = self.color1
|
self.fill((0, 0, 0))
|
||||||
self.color1 = (0,0,0)
|
|
||||||
self.fill()
|
|
||||||
self.color1 = color
|
|
||||||
|
|
||||||
def on(self):
|
def on(self):
|
||||||
color = self.color1
|
self.fill(self.apply_brightness(self.colors[0]))
|
||||||
self.color1 = self.apply_brightness(self.color1)
|
|
||||||
self.fill()
|
|
||||||
self.color1 = color
|
|
||||||
|
|
||||||
|
|
||||||
def color_wipe_step(self):
|
def color_wipe_step(self):
|
||||||
color = self.apply_brightness(self.color1)
|
color = self.apply_brightness(self.colors[0])
|
||||||
current_time = utime.ticks_ms()
|
current_time = utime.ticks_ms()
|
||||||
if utime.ticks_diff(current_time, self.last_update) >= self.delay:
|
if utime.ticks_diff(current_time, self.last_update) >= self.delay:
|
||||||
if self.pattern_step < self.num_leds:
|
if self.pattern_step < self.num_leds:
|
||||||
@@ -129,7 +235,7 @@ class Patterns:
|
|||||||
if utime.ticks_diff(current_time, self.last_update) >= self.delay:
|
if utime.ticks_diff(current_time, self.last_update) >= self.delay:
|
||||||
for i in range(self.num_leds):
|
for i in range(self.num_leds):
|
||||||
if (i + self.pattern_step) % 3 == 0:
|
if (i + self.pattern_step) % 3 == 0:
|
||||||
self.n[i] = self.apply_brightness(self.color1)
|
self.n[i] = self.apply_brightness(self.colors[0])
|
||||||
else:
|
else:
|
||||||
self.n[i] = (0, 0, 0)
|
self.n[i] = (0, 0, 0)
|
||||||
self.n.write()
|
self.n.write()
|
||||||
@@ -140,152 +246,69 @@ class Patterns:
|
|||||||
current_time = utime.ticks_ms()
|
current_time = utime.ticks_ms()
|
||||||
if utime.ticks_diff(current_time, self.last_update) >= self.delay:
|
if utime.ticks_diff(current_time, self.last_update) >= self.delay:
|
||||||
if self.pattern_step % 2 == 0:
|
if self.pattern_step % 2 == 0:
|
||||||
for i in range(self.num_leds):
|
self.fill(self.apply_brightness(self.colors[0]))
|
||||||
self.n[i] = self.apply_brightness(self.color1)
|
|
||||||
else:
|
else:
|
||||||
for i in range(self.num_leds):
|
self.fill((0, 0, 0))
|
||||||
self.n[i] = (0, 0, 0)
|
|
||||||
self.n.write()
|
|
||||||
self.pattern_step = (self.pattern_step + 1) % 2
|
|
||||||
self.last_update = current_time
|
|
||||||
|
|
||||||
def random_color_wipe_step(self):
|
|
||||||
current_time = utime.ticks_ms()
|
|
||||||
if utime.ticks_diff(current_time, self.last_update) >= self.delay:
|
|
||||||
color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
|
|
||||||
if self.pattern_step < self.num_leds:
|
|
||||||
for i in range(self.num_leds):
|
|
||||||
self.n[i] = (0, 0, 0)
|
|
||||||
self.n[self.pattern_step] = self.apply_brightness(color)
|
|
||||||
self.n.write()
|
|
||||||
self.pattern_step += 1
|
|
||||||
else:
|
|
||||||
self.pattern_step = 0
|
|
||||||
self.last_update = current_time
|
|
||||||
|
|
||||||
def random_rainbow_cycle_step(self):
|
|
||||||
current_time = utime.ticks_ms()
|
|
||||||
if utime.ticks_diff(current_time, self.last_update) >= self.delay:
|
|
||||||
def wheel(pos):
|
|
||||||
if pos < 85:
|
|
||||||
return (pos * 3, 255 - pos * 3, 0)
|
|
||||||
elif pos < 170:
|
|
||||||
pos -= 85
|
|
||||||
return (255 - pos * 3, 0, pos * 3)
|
|
||||||
else:
|
|
||||||
pos -= 170
|
|
||||||
return (0, pos * 3, 255 - pos * 3)
|
|
||||||
|
|
||||||
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
|
|
||||||
self.n[i] = self.apply_brightness(wheel(rc_index & 255))
|
|
||||||
self.n.write()
|
|
||||||
self.pattern_step = (self.pattern_step + 1) % 256
|
|
||||||
self.last_update = current_time
|
|
||||||
|
|
||||||
def random_theater_chase_step(self):
|
|
||||||
current_time = utime.ticks_ms()
|
|
||||||
if utime.ticks_diff(current_time, self.last_update) >= self.delay:
|
|
||||||
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:
|
|
||||||
self.n[i] = self.apply_brightness(color)
|
|
||||||
else:
|
|
||||||
self.n[i] = (0, 0, 0)
|
|
||||||
self.n.write()
|
|
||||||
self.pattern_step = (self.pattern_step + 1) % 3
|
|
||||||
self.last_update = current_time
|
|
||||||
|
|
||||||
def random_blink_step(self):
|
|
||||||
current_time = utime.ticks_ms()
|
|
||||||
if utime.ticks_diff(current_time, self.last_update) >= self.delay:
|
|
||||||
color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
|
|
||||||
if self.pattern_step % 2 == 0:
|
|
||||||
for i in range(self.num_leds):
|
|
||||||
self.n[i] = self.apply_brightness(color)
|
|
||||||
else:
|
|
||||||
for i in range(self.num_leds):
|
|
||||||
self.n[i] = (0, 0, 0)
|
|
||||||
self.n.write()
|
|
||||||
self.pattern_step = (self.pattern_step + 1) % 2
|
self.pattern_step = (self.pattern_step + 1) % 2
|
||||||
self.last_update = current_time
|
self.last_update = current_time
|
||||||
|
|
||||||
def color_transition_step(self):
|
def color_transition_step(self):
|
||||||
current_time = utime.ticks_ms()
|
current_time = utime.ticks_ms()
|
||||||
if utime.ticks_diff(current_time, self.last_update) >= self.delay:
|
|
||||||
# Calculate transition factor based on elapsed time
|
|
||||||
transition_factor = (self.pattern_step * 100) / self.transition_duration
|
|
||||||
if transition_factor > 100:
|
|
||||||
transition_factor = 100
|
|
||||||
color = self.interpolate_color(self.color1, self.color2, transition_factor / 100)
|
|
||||||
|
|
||||||
# Apply the interpolated color to all LEDs
|
|
||||||
for i in range(self.num_leds):
|
|
||||||
self.n[i] = self.apply_brightness(color)
|
|
||||||
self.n.write()
|
|
||||||
|
|
||||||
self.pattern_step += self.delay
|
# Check for hold duration first
|
||||||
if self.pattern_step > self.transition_duration:
|
if utime.ticks_diff(current_time, self.hold_start_time) < self.hold_duration:
|
||||||
self.pattern_step = 0
|
# Still in hold phase, just display the current solid color
|
||||||
|
self.fill(self.apply_brightness(self.current_color))
|
||||||
|
self.last_update = current_time # Keep updating last_update to avoid skipping frames
|
||||||
|
return
|
||||||
|
|
||||||
|
# If hold duration is over, proceed with transition
|
||||||
|
if utime.ticks_diff(current_time, self.last_update) >= self.delay:
|
||||||
|
num_colors = len(self.colors)
|
||||||
|
if num_colors < 2:
|
||||||
|
# Should not happen if select handles it, but as a safeguard
|
||||||
|
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]
|
||||||
|
|
||||||
|
# Calculate interpolation factor (0.0 to 1.0)
|
||||||
|
# transition_step goes from 0 to transition_duration - 1
|
||||||
|
if self.transition_duration > 0:
|
||||||
|
interp_factor = self.transition_step / self.transition_duration
|
||||||
|
else:
|
||||||
|
interp_factor = 1.0 # Immediately transition if duration is zero
|
||||||
|
|
||||||
|
# Interpolate each color component
|
||||||
|
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 # Advance the transition step by the delay
|
||||||
|
|
||||||
|
if self.transition_step >= self.transition_duration:
|
||||||
|
# Transition complete, move to the next color and reset for hold phase
|
||||||
|
self.current_color_idx = to_color_idx
|
||||||
|
self.current_color = self.colors[self.current_color_idx] # Ensure current_color is the exact target color
|
||||||
|
self.transition_step = 0 # Reset transition progress
|
||||||
|
self.hold_start_time = current_time # Start hold phase for the new color
|
||||||
|
|
||||||
self.last_update = current_time
|
self.last_update = current_time
|
||||||
|
|
||||||
def interpolate_color(self, color1, color2, factor):
|
def flicker_step(self):
|
||||||
return (
|
|
||||||
int(color1[0] + (color2[0] - color1[0]) * factor),
|
|
||||||
int(color1[1] + (color2[1] - color1[1]) * factor),
|
|
||||||
int(color1[2] + (color2[2] - color1[2]) * factor)
|
|
||||||
)
|
|
||||||
|
|
||||||
def two_steps_forward_one_step_back_step(self):
|
|
||||||
current_time = utime.ticks_ms()
|
current_time = utime.ticks_ms()
|
||||||
if utime.ticks_diff(current_time, self.last_update) >= self.delay:
|
if utime.ticks_diff(current_time, self.last_update) >= self.delay/5:
|
||||||
# Move forward 2 steps and backward 1 step
|
base_color = self.colors[0]
|
||||||
if self.direction == 1: # Moving forward
|
# Increase the range for flicker_brightness_offset
|
||||||
if self.scanner_position < self.num_leds - 2:
|
# Changed from self.brightness // 4 to self.brightness // 2 (or even self.brightness for max intensity)
|
||||||
self.scanner_position += 2 # Move forward 2 steps
|
flicker_brightness_offset = random.randint(-int(self.brightness // 1.5), int(self.brightness // 1.5))
|
||||||
else:
|
flicker_brightness = max(0, min(255, self.brightness + flicker_brightness_offset))
|
||||||
self.direction = -1 # Change direction to backward
|
|
||||||
else: # Moving backward
|
|
||||||
if self.scanner_position > 0:
|
|
||||||
self.scanner_position -= 1 # Move backward 1 step
|
|
||||||
else:
|
|
||||||
self.direction = 1 # Change direction to forward
|
|
||||||
|
|
||||||
# Set all LEDs to off
|
|
||||||
for i in range(self.num_leds):
|
|
||||||
self.n[i] = (0, 0, 0)
|
|
||||||
|
|
||||||
# Set the current position to the color
|
|
||||||
self.n[self.scanner_position] = self.apply_brightness(self.color1)
|
|
||||||
|
|
||||||
# Apply the color transition
|
|
||||||
transition_factor = (self.pattern_step * 100) / self.transition_duration
|
|
||||||
if transition_factor > 100:
|
|
||||||
transition_factor = 100
|
|
||||||
color = self.interpolate_color(self.color1, self.color2, transition_factor / 100)
|
|
||||||
self.n[self.scanner_position] = self.apply_brightness(color)
|
|
||||||
|
|
||||||
self.n.write()
|
|
||||||
self.pattern_step += self.delay
|
|
||||||
if self.pattern_step > self.transition_duration:
|
|
||||||
self.pattern_step = 0
|
|
||||||
|
|
||||||
|
flicker_color = self.apply_brightness(base_color, brightness_override=flicker_brightness)
|
||||||
|
self.fill(flicker_color)
|
||||||
self.last_update = current_time
|
self.last_update = current_time
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
p = Patterns(4, 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))
|
|
||||||
|
@@ -9,16 +9,21 @@ class Settings(dict):
|
|||||||
def __init__(self):
|
def __init__(self):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.load() # Load settings from file during initialization
|
self.load() # Load settings from file during initialization
|
||||||
|
if self["color_order"] == "rbg": self.color_order = (1, 5, 3)
|
||||||
|
else: self.color_order = (1, 3, 5)
|
||||||
|
|
||||||
def set_defaults(self):
|
def set_defaults(self):
|
||||||
|
self["led_pin"] = 10
|
||||||
self["num_leds"] = 50
|
self["num_leds"] = 50
|
||||||
self["pattern"] = "on"
|
self["pattern"] = "on"
|
||||||
self["color1"] = "#00ff00"
|
self["color1"] = "#00ff00"
|
||||||
self["color2"] = "#ff0000"
|
self["color2"] = "#ff0000"
|
||||||
self["delay"] = 100
|
self["delay"] = 100
|
||||||
self["brightness"] = 10
|
self["brightness"] = 10
|
||||||
|
self["color_order"] = "rgb"
|
||||||
self["name"] = f"led-{ubinascii.hexlify(wifi.get_mac()).decode()}"
|
self["name"] = f"led-{ubinascii.hexlify(wifi.get_mac()).decode()}"
|
||||||
self["ap_password"] = ""
|
self["ap_password"] = ""
|
||||||
|
self["id"] = 0
|
||||||
|
|
||||||
def save(self):
|
def save(self):
|
||||||
try:
|
try:
|
||||||
@@ -40,6 +45,54 @@ class Settings(dict):
|
|||||||
self.set_defaults()
|
self.set_defaults()
|
||||||
self.save()
|
self.save()
|
||||||
|
|
||||||
|
def set_settings(self, data, patterns, save):
|
||||||
|
try:
|
||||||
|
print(data)
|
||||||
|
for key, value in data.items():
|
||||||
|
print(key, value)
|
||||||
|
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(self["led_pin"], value)
|
||||||
|
elif key == "pattern":
|
||||||
|
if not patterns.select(value):
|
||||||
|
return "Pattern doesn't exist", 400
|
||||||
|
elif key == "delay":
|
||||||
|
delay = int(data["delay"])
|
||||||
|
patterns.set_delay(delay)
|
||||||
|
elif key == "brightness":
|
||||||
|
brightness = int(data["brightness"])
|
||||||
|
patterns.set_brightness(brightness)
|
||||||
|
elif key == "name":
|
||||||
|
self[key] = value
|
||||||
|
self.save()
|
||||||
|
machine.reset()
|
||||||
|
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
|
||||||
|
except (KeyError, ValueError):
|
||||||
|
return "Bad request", 400
|
||||||
|
|
||||||
# Example usage
|
# Example usage
|
||||||
def main():
|
def main():
|
||||||
settings = Settings()
|
settings = Settings()
|
||||||
@@ -53,39 +106,7 @@ def main():
|
|||||||
print(f"Loaded number of LEDs: {new_settings['num_leds']}")
|
print(f"Loaded number of LEDs: {new_settings['num_leds']}")
|
||||||
print(settings)
|
print(settings)
|
||||||
|
|
||||||
def set_settings(raw_json, settings, patterns):
|
|
||||||
patterns.sync()
|
|
||||||
try:
|
|
||||||
data = json.loads(raw_json)
|
|
||||||
print(data)
|
|
||||||
for key, value in data.items():
|
|
||||||
print(key, value)
|
|
||||||
if key == "color1":
|
|
||||||
patterns.set_color1(tuple(int(value[i:i+2], 16) for i in (1, 3, 5))) # Convert hex to RGB
|
|
||||||
elif key == "color2":
|
|
||||||
patterns.set_color2(tuple(int(value[i:i+2], 16) for i in (1, 3, 5))) # Convert hex to RGB
|
|
||||||
elif key == "num_leds":
|
|
||||||
patterns.update_num_leds(4, value)
|
|
||||||
elif key == "pattern":
|
|
||||||
if not patterns.select(value):
|
|
||||||
return "Pattern doesn't exist", 400
|
|
||||||
elif key == "delay":
|
|
||||||
delay = int(data["delay"])
|
|
||||||
patterns.set_delay(delay)
|
|
||||||
elif key == "brightness":
|
|
||||||
brightness = int(data["brightness"])
|
|
||||||
patterns.set_brightness(brightness)
|
|
||||||
elif key == "name":
|
|
||||||
settings[key] = value
|
|
||||||
settings.save()
|
|
||||||
machine.reset()
|
|
||||||
else:
|
|
||||||
return "Invalid key", 400
|
|
||||||
settings[key] = value
|
|
||||||
settings.save()
|
|
||||||
return "OK", 200
|
|
||||||
except (KeyError, ValueError):
|
|
||||||
return "Bad request", 400
|
|
||||||
|
|
||||||
# Run the example
|
# Run the example
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
@@ -98,3 +98,12 @@ input[type="range"]::-moz-range-thumb {
|
|||||||
#connection-status.closed {
|
#connection-status.closed {
|
||||||
background-color: red;
|
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 */
|
||||||
|
}
|
||||||
|
@@ -150,6 +150,30 @@ async function updateName(event) {
|
|||||||
sendWebSocketData({ name: name });
|
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) {
|
function createPatternButtons(patterns) {
|
||||||
const container = document.getElementById("pattern_buttons");
|
const container = document.getElementById("pattern_buttons");
|
||||||
container.innerHTML = ""; // Clear previous buttons
|
container.innerHTML = ""; // Clear previous buttons
|
||||||
@@ -184,11 +208,17 @@ document.addEventListener("DOMContentLoaded", async function () {
|
|||||||
.getElementById("num_leds_form")
|
.getElementById("num_leds_form")
|
||||||
.addEventListener("submit", updateNumLeds);
|
.addEventListener("submit", updateNumLeds);
|
||||||
document.getElementById("name_form").addEventListener("submit", updateName);
|
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("delay").addEventListener("touchend", updateDelay);
|
||||||
document
|
document
|
||||||
.getElementById("brightness")
|
.getElementById("brightness")
|
||||||
.addEventListener("touchend", updateBrightness);
|
.addEventListener("touchend", updateBrightness);
|
||||||
|
|
||||||
|
document.getElementById("rgb").addEventListener("change", handleRadioChange);
|
||||||
|
document.getElementById("rbg").addEventListener("change", handleRadioChange);
|
||||||
document.querySelectorAll(".pattern_button").forEach((button) => {
|
document.querySelectorAll(".pattern_button").forEach((button) => {
|
||||||
console.log(button.value);
|
console.log(button.value);
|
||||||
button.addEventListener("click", async (event) => {
|
button.addEventListener("click", async (event) => {
|
||||||
|
@@ -4,12 +4,12 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<title>LED Control</title>
|
<title>{{settings['name']}}</title>
|
||||||
<script src="static/main.js"></script>
|
<script src="static/main.js"></script>
|
||||||
<link rel="stylesheet" href="static/main.css" />
|
<link rel="stylesheet" href="static/main.css" />
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<h1>Control LEDs</h1>
|
<h1>{{settings['name']}}</h1>
|
||||||
<button onclick="selectControls()">Controls</button>
|
<button onclick="selectControls()">Controls</button>
|
||||||
<button onclick="selectSettings()">Settings</button>
|
<button onclick="selectSettings()">Settings</button>
|
||||||
|
|
||||||
@@ -79,6 +79,16 @@
|
|||||||
/>
|
/>
|
||||||
<input type="submit" value="Update Name" />
|
<input type="submit" value="Update Name" />
|
||||||
</form>
|
</form>
|
||||||
|
<form id="id_form" method="post" action="/id">
|
||||||
|
<label for="id">ID:</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
id="id"
|
||||||
|
name="id"
|
||||||
|
value="{{settings['id']}}"
|
||||||
|
/>
|
||||||
|
<input type="submit" value="Update ID" />
|
||||||
|
</form>
|
||||||
<!-- Separate form for submitting num_leds -->
|
<!-- Separate form for submitting num_leds -->
|
||||||
<form id="num_leds_form" method="post" action="/num_leds">
|
<form id="num_leds_form" method="post" action="/num_leds">
|
||||||
<label for="num_leds">Number of LEDs:</label>
|
<label for="num_leds">Number of LEDs:</label>
|
||||||
@@ -90,6 +100,23 @@
|
|||||||
/>
|
/>
|
||||||
<input type="submit" value="Update Number of LEDs" />
|
<input type="submit" value="Update Number of LEDs" />
|
||||||
</form>
|
</form>
|
||||||
|
<form id="led_pin_form" method="post" action="/led_pin">
|
||||||
|
<label for="num_leds">Led pin:</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
id="led_pin"
|
||||||
|
name="led_pin"
|
||||||
|
value="{{settings['led_pin']}}"
|
||||||
|
/>
|
||||||
|
<input type="submit" value="Update Led Pin" />
|
||||||
|
</form>
|
||||||
|
<form id="color_order_form">
|
||||||
|
<label for="rgb">RGB:</label>
|
||||||
|
<input type="radio" id="rgb" name="color_order" value="rgb" {{'checked' if settings["color_order"]=="rgb" else ''}} />
|
||||||
|
<label for="rbg">RBG</label>
|
||||||
|
<input type="radio" id="rbg" name="color_order" value="rbg" {{'checked' if settings["color_order"]=="rbg" else ''}}/>
|
||||||
|
</form>
|
||||||
|
|
||||||
<p>Mac address: {{mac}}</p>
|
<p>Mac address: {{mac}}</p>
|
||||||
</div>
|
</div>
|
||||||
<div id="connection-status"></div>
|
<div id="connection-status"></div>
|
||||||
|
@@ -2,7 +2,6 @@ from microdot import Microdot, send_file, Response
|
|||||||
from microdot.utemplate import Template
|
from microdot.utemplate import Template
|
||||||
from microdot.websocket import with_websocket
|
from microdot.websocket import with_websocket
|
||||||
import machine
|
import machine
|
||||||
from settings import set_settings
|
|
||||||
import wifi
|
import wifi
|
||||||
import json
|
import json
|
||||||
|
|
||||||
@@ -26,7 +25,7 @@ def web(settings, patterns):
|
|||||||
def settings_handler(request):
|
def settings_handler(request):
|
||||||
# Keep the POST handler for compatibility or alternative usage if needed
|
# Keep the POST handler for compatibility or alternative usage if needed
|
||||||
# For WebSocket updates, the /ws handler is now primary
|
# For WebSocket updates, the /ws handler is now primary
|
||||||
return set_settings(request.body.decode('utf-8'), settings, patterns)
|
return settings.set_settings(request.body.decode('utf-8'), patterns)
|
||||||
|
|
||||||
@app.route("/ws")
|
@app.route("/ws")
|
||||||
@with_websocket
|
@with_websocket
|
||||||
@@ -34,8 +33,9 @@ def web(settings, patterns):
|
|||||||
while True:
|
while True:
|
||||||
data = await ws.receive()
|
data = await ws.receive()
|
||||||
if data:
|
if data:
|
||||||
|
|
||||||
# Process the received data
|
# Process the received data
|
||||||
_, status_code = set_settings(data, settings, patterns)
|
_, status_code = settings.set_settings(json.loads(data), patterns, True)
|
||||||
#await ws.send(status_code)
|
#await ws.send(status_code)
|
||||||
else:
|
else:
|
||||||
break
|
break
|
||||||
|
11
src/wifi.py
11
src/wifi.py
@@ -2,14 +2,15 @@ import network
|
|||||||
from time import sleep
|
from time import sleep
|
||||||
|
|
||||||
def connect(ssid, password, ip, gateway):
|
def connect(ssid, password, ip, gateway):
|
||||||
if ssid is None or password is None:
|
|
||||||
print("Missing ssid or password")
|
|
||||||
return None
|
|
||||||
try:
|
try:
|
||||||
sta_if = network.WLAN(network.STA_IF)
|
sta_if = network.WLAN(network.STA_IF)
|
||||||
if ip is not None and gateway is not None:
|
|
||||||
sta_if.ifconfig((ip, '255.255.255.0', gateway, '1.1.1.1'))
|
|
||||||
if not sta_if.isconnected():
|
if not sta_if.isconnected():
|
||||||
|
if ssid == "" or password == "":
|
||||||
|
print("Missing ssid or password")
|
||||||
|
return None
|
||||||
|
if ip != "" and gateway != "":
|
||||||
|
sta_if.ifconfig((ip, '255.255.255.0', gateway, '1.1.1.1'))
|
||||||
print('connecting to network...')
|
print('connecting to network...')
|
||||||
sta_if.active(True)
|
sta_if.active(True)
|
||||||
sta_if.connect(ssid, password)
|
sta_if.connect(ssid, password)
|
||||||
|
Reference in New Issue
Block a user